我有一个包含如下文档的集合:
{
_id : "abcd",
name : "Tom",
myArray : [
{
field1 : "",
field2 : ""
}
]
},
{
_id : "efgh",
name : "Jerry"
}
我有一个新对象需要添加到myArray
中。我想编写一个查询来仅更新一个文档。
如果查询匹配具有_id : "abcd"
的文档,则将新对象推入myArray
字段中:
{
_id : "abcd",
name : "Tom",
myArray : [
{
field1 : "",
field2 : ""
},
{
// new object
}
]
}
如果查询与 _id : "efgh"
匹配,则在其中创建一个新对象的 myArray
字段:
{
_id : "efgh",
name : "Jerry"
myArray : [
{
// new object
}
]
}
我该怎么实现这个?
$push
一个数组到一个不存在的文档中,它会创建一个新的数组。如果已经存在一个数组,则新的文档将被追加到该数组中。所以要么你根本没有尝试过,要么你的问题中仍然缺少一些关于你真正想做什么的信息。 - Blakes Seven