我有这样的架构:
({
_id:id ,
createdAt: new Date(),
name:name,
friends : [{name:"tommy",children:[{name:"sarah",age:12}]}],
dogs : [{}]
});
其中朋友的“名字”实际上是一个数字。
我正在使用以下方式更新所述数组:
var obj = {name:"tommy",children:[{name:"ds",age:12},{name:"two",age:12}]};
var bulk = db.t.initializeUnorderedBulkOp();
bulk.find({"friends.name":obj.name}).update({$addToSet:{"friends.$.children":{$each:obj.children}}});
bulk.find({"friends.name":{$ne:obj.name}}).update({$push:{"friends":obj}});
bulk.execute();
我正在努力使得friends数组总是按照“name”attribut按升序排序(记住它实际上是一个数字),这样朋友的输出数组总是排序:
friends : [{name:34,children:[{name:"sarah",age:12}]},{name:38,children:[{name:"sarah",age:12}]},{name:95,children:[{name:"sarah",age:12}]}]
正如doc example The sort document refers directly to the field in the documents and does not reference the containing array field我尝试添加$sort: { name: 1 }
,但它没有做任何事情而且数组保持不变:
var obj = {name:"tommy",children:[{name:"ds",age:12},{name:"two",age:12}]};
var bulk = db.t.initializeUnorderedBulkOp();
bulk.find({"friends.name":obj.name}).update({$addToSet:{"friends.$.children":{$each:obj.children,$sort: { name: 1 }}}});
bulk.find({"friends.name":{$ne:obj.name}}).update({$push:{"friends":obj,$sort: { name: 1 }}});
bulk.execute();
任何人都可以看到我的错误吗?是否可以对批量操作进行排序?
由于
答案 0 :(得分:0)
找到解决方案:
Collection.update({"_id":id},{$push: {"friends": { "$each": [], "$sort": { "name": 1 }}}});