I would like to:
1) find documents
2) each of the found documents include an array, I would like to insert a new array element into the array. If the array element already exists, do nothing (do not insert a new element into the array).
I've played with aggregation however I can't seem to find an insert function?
Data:
{
"_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")
}
]
}
Insert:
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);
});
});
Update.
Tried the following also not willing to insert :/
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);
});
});
如user3100115所述,您应该使用如下更新:
db.collection.update({cell:1},{$addToSet:{sessions:{id: 'test'}}},{multi:true})
Using co-monk:
yield users.update({
cell: 1
}, {
$addToSet: {
sessions: {
id: 'test'
}
}
}, {
multi: true
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.