我有看起来像这样的mongo db集合:
({
_id:id ,
createdAt: new Date(),
name:name,
friends : [{name:"tommy",children:[{name:"sarah",age:12}]}],
dogs : [{}]
});
如果名称不存在,我希望能够在friends数组中插入一个新元素,并向该新数组插入一个children元素。
如果我要添加一个新的朋友john和一个孩子nathaly,我希望输出为
({
_id:id ,
createdAt: new Date(),
name:name,
friends : [{name:"tommy",children:[{name:"sarah",age:12}]},{name:"john",children:[{name:"natahly",age:20}]}],
dogs : [{}]
});
如果朋友汤米已经存在,我只希望将子代添加到子代数组,现在将输出
({
_id:id ,
createdAt: new Date(),
name:name,
friends : [{name:"tommy",children:[{name:"sarah",age:12},{name:"newchild",age:99}]},{name:"john",children:[{name:"natahly",age:20}]}],
dogs : [{}]
});
我已经尝试了很多事情,因此无法列出。
目前,我正在尝试混合所有方法
// if `friends` is `[]`, push the empty children firstly through addToSet
var bulk = Directory.rawCollection().initializeUnorderedBulkOp();
bulk.find({_id: id, 'friends.name': {$exists: false}}).updateOne(
{$addToSet: {friends: {name: name_var, children: []}});
Meteor.wrapAsync(bulk.execute)();
// then Since previous step create the children array for said friend only if it doesn't already exist i'm just trying to update said friend with the new child
Directory.update(
{ _id: id,"friends.name": name_var },
{ $push: { "friends.$.children": {name:"sarah",age:12}
}}})
(我也尝试过使用“ friends.children”而不是“ friends。$。children”,但是我得到了另一个错误)
这应该可以解决我的三个问题,但是我遇到了问题,我想知道自己是否走对了。你们每个人都有任何想法,因为这至少应该可以添加孩子,但事实并非如此。
Errors : MongoError: The field 'friends.0.children' must be an array but is of type Object in document {_id: "0"} # when friends.$.children"
MongoError: cannot use the part (Friends of Friends.childrens) to traverse the element when friends.children"
一种方法是
insert/update
该对象可以一次插入多个子级。
var obj = {name:"tommy",children:[{name:"ds",age:12},{name:"two",age:12}]};
Bulk API
。这里的操作顺序无关紧要。
var bulk = db.t.initializeUnorderedBulkOp();
update
只有子记录已经具有的子文档name
。使用$addToSet
运算符来维护唯一记录,并一次$each
添加多个孩子。
bulk.find({"friends.name":obj.name})
.update({$addToSet:{"friends.$.children":{$each:obj.children}}});
update
那些不具有子文件。$push
如果文档没有一个对象,则为整个对象。
bulk.find({"friends.name":{$ne:obj.name}})
.update({$push:{"friends":obj}});
bulk.execute();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句