如果我在集合中包含此文档,我该如何进行部分插入?
集合
{
"_id" : "123",
"title" : "Green Tree",
"detail" : [
{
"title" : "Just a title",
"content" : "Content",
"reference" : 456
}
]
}
如果我有一个具有相同第一级标题的对象,则应该添加详细信息。所以如果我要添加这两个对象:
var newObject_1 = {
"title" : "Green Tree",
"detail" : [
{
"title" : "Just another title",
"content" : "And another content",
"reference" : 456
}
]
}
var newObject_2 = {
"title" : "Red Car",
"detail" : [
{
"title" : "title",
"content" : "content",
"reference" : 456
}
]
}
Collection.insert(newObject_1);
Collection.insert(newObject_2);
结果应为
{
"_id" : "123",
"title" : "Green Tree",
"detail" : [
{
"title" : "Just a title",
"content" : "Content",
"reference" : 456
},
{
"title" : "Just another title",
"content" : "And another content",
"reference" : 456
}
]
}
{
"_id" : "124",
"title" : "Red Car",
"detail" : [
{
"title" : "title",
"content" : "content",
"reference" : 456
}
]
}
如果细节内容相同,则根本不会发生任何事情。如果标题不同,我只需Collection.insert(newObject);
完全添加数据。
答案 0 :(得分:1)
也许喜欢吵架?
MyCollection.upsert(
{ name: 'green-tree' },
{
$setOnInsert: { details: [] },
$set: { 'details': yourObj.details },
}
)
基本上,它会尝试找到提供名称的文档。如果找到它,它将执行以下选项。否则,它将插入它并执行指定的操作。