[英]MongoDB update query in subarray
An update in the array of objects inside another array of objects.另一个对象数组中的对象数组的更新。
mongodb field that I'm working on:我正在处理的 mongodb 字段:
otherFields: values,
tasks: [
{
_id: mongodb.objectID(),
title: string,
items:[{
_id: mongodb.objectID(),
title: string,
completed: boolean //field need to be update.
}]
},
{}...
],
otherFields: value
sample mongodb document样品 mongodb 文件
I need to find the document using the task_id and the item_id and update a completed field in item of a task.我需要使用task_id和item_id查找文档并更新任务项目中的已完成字段。 Using the mongoose findOneAndUpdate method使用 mongoose findOneAndUpdate方法
const path = "tasks.$.items." + item_id + "completed";
collectionName.findOneAndUpdate(
{ _id: req.user._id, "tasks._id": taskID },
{ $set: { [path]: true }});
The above query doesn't work!!!以上查询无效!!!
There is no need to use multiple query conditions, since you'd like to update a specific item that has an unique ID.无需使用多个查询条件,因为您想更新具有唯一 ID 的特定项目。 Therefore you could use something along the lines:因此,您可以使用类似的东西:
collectionName.findOneAndUpdate(
{ 'tasks.items._id': itemID },
...
);
Keep in mind this structure is far away from optimized as it would basically look through the entire database...请记住,这种结构远未优化,因为它基本上会查看整个数据库......
Also now that I think of it, you'd also have issue with the update, as there are two nested arrays within the document.现在我想起来了,您也会对更新有疑问,因为文档中有两个嵌套的 arrays。 Read more here: How to Update Multiple Array Elements in mongodb在此处阅读更多内容: 如何更新 mongodb 中的多个阵列元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.