如何根据 req.body 发送的多个条件更新文档的多个字段(maxLength、maxBreadth 或 maxArea)?
我想存储从请求遇到的最大长度,宽,区域,并将其存储在数据库中。在这种情况下,任何内容都可以最大,并且基于我要在数据库中仅更新该特定字段的最大值。
const body = {
oID: 123, // Primary key
length: 50,
breadth: 50
};
const { length, breadth } = body;
const currentArea = length * breadth;
await totalArea.updateOne(
{ oID: 123 },
{
$set: { $maxLength: maxLength < length ? length : $maxLength }, // I want to update the docs based on mongo query only since this won't work.
$set: { $maxBreadth: maxBreadth < breadth ? breadth : $maxBreadth }, // I want to update the docs based on mongo query only since this won't work.
$set: { $maxArea: maxArea < currentArea ? currentArea : $maxArea } // I want to update the docs based on mongo query only since this won't work.
},
{ upsert: true }
);
在上面的示例中,我已经使用三元运算符演示了逻辑,我想使用MongoDB查询执行相同的操作。 IE在将其与数据库中的现有字段进行比较时更新特定字段,并在满足条件的情况下对其进行更新。
I want to store maximum length, breadth, area ever encountered from a request and store it in the database. In this case, anything can be maximum and based on that I want to update max values in the database for that particular field only.
const body = {
oID: 123, // Primary key
length: 50,
breadth: 50
};
const { length, breadth } = body;
const currentArea = length * breadth;
await totalArea.updateOne(
{ oID: 123 },
{
$set: { $maxLength: maxLength < length ? length : $maxLength }, // I want to update the docs based on mongo query only since this won't work.
$set: { $maxBreadth: maxBreadth < breadth ? breadth : $maxBreadth }, // I want to update the docs based on mongo query only since this won't work.
$set: { $maxArea: maxArea < currentArea ? currentArea : $maxArea } // I want to update the docs based on mongo query only since this won't work.
},
{ upsert: true }
);
In the above example, I have demonstrated the logic using ternary operator and I want to perform the same operation using mongoDB query. i.e update a particular field while comparing it to existing fields from the database and update it if it satisfies the condition.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我发现这工作正常。感谢@Mehari Mamo的评论。
I found this to be working correctly. Thanks to @Mehari Mamo's comment.
如果我正确理解,您需要这样的东西:
您可以检查在这里。
第二步上的
[]
允许您访问文档字段的当前值,因为这是一个聚合管道。If I understand correctly, you want something like this:
You can check it here .
The
[]
on the second step allows you to access the current values of the document fields, as this is an aggregation pipeline.