我希望:
1)找到文档
2)找到的每个文档都包含一个数组,我想将一个新的数组元素插入到数组中。如果数组元素已经存在,则不执行任何操作(不要将新元素插入到数组中)。
我已经尝试过聚合,但似乎找不到插入函数?
数据:
{
"_id" : ObjectId("560c24b853b558856ef193a4"),
"name" : "ирина",
"pic" : "",
"language" : ObjectId("560c24b853b558856ef193a2"),
"cell" : 1,
"local" : {
"email" : "ирина@mail.com",
"password" : "12345"
},
"sessions" : [ // <--- this is the array I would like to insert a new element into
{
"id" : ObjectId("560c24b853b558856ef193a5")
}
]
}
插入:
yield new Promise(function (resolve, reject) {
users.col.aggregate([
{
$match: {
'cell': socket.cell
}
},
{
// <--- insert here?
}
],
function (err, res) {
if (err === null)
resolve(res);
reject(err);
});
});
更新。
尝试下面的方法仍然不愿插入 :/
yield new Promise(function (resolve, reject) {
var bulk = users.col.initializeUnorderedBulkOp();
bulk.find({
cell: 1
}).update({
$addToSet: {
sessions: {
id: 'test'
}
}
});
bulk.execute(function (err, res) {
console.log(res);
resolve(res);
});
});
update
就可以了。 - styvane$match
一样,但是$update
? - basickarl