[英]update one element of array of objects in mongodb
I have the following documents:我有以下文件:
{
_id: ObjectId('111111111111111111114444'),
books: [
{
id: ObjectId('111111111111111111113333'),
pictures: []
},
{
id: ObjectId('111111111111111111112222'),
pictures: []
}
],
// others attributes
}
What I need to do is to add an element to pictures
.我需要做的是在
pictures
添加一个元素。 Keep in mind that I have the documentId
which is the id of the document, and the bookId
which is the Id of an element of books .请记住,我有
documentId
是documentId
的 id,而bookId
是books元素的 Id。
If I want to add the element {description: "nice picture"}
to the document 111111111111111111114444 in the book 111111111111111111113333 , the updated document would look like如果我想将元素
{description: "nice picture"}
到1111111111111111111114444一书中的文档1111111111111111111113333 ,更新后的文档看起来像
{
_id: ObjectId('111111111111111111114444'),
books: [
{
id: ObjectId('111111111111111111113333'),
pictures: [
{
description: "nice picture"
}
]
},
{
id: ObjectId('111111111111111111112222'),
pictures: []
}
],
// others attributes
}
Query询问
id=2
merge objects, with the pictures containing the new elementid=2
合并对象,则在书籍上映射,其中图片包含新元素id=2
dont change the bookid=2
不要换书*i used 1,2,3 for ids (its the same code) *我使用 1,2,3 作为 ids(它的代码相同)
update({"_id" : 1},
[{"$set":
{"books":
{"$map":
{"input": "$books",
"in":
{"$cond":
[{"$eq": ["$$book.id", 2]},
{"$mergeObjects":
["$$book",
{"pictures":
{"$concatArrays":
["$$book.pictures", [{"description": "nice picture"}]]}}]},
"$$book"]},
"as": "book"}}}}])
Edit编辑
Query询问
update({"_id" : 1},
[{"$set":
{"books":
{"$map":
{"input": "$books",
"in":
{"$cond":
[{"$eq": ["$$book.id", 2]},
{"$mergeObjects":
["$$book",
{"pictures":
{"$concatArrays":
[{"$cond":
[{"$isArray": ["$$book.pictures"]}, "$$book.pictures",
[]]},
[{"description": "nice picture"}]]}}]},
"$$book"]},
"as": "book"}}}}])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.