简体   繁体   中英

Mongodb find and insert

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
});

You can use Bulk operations, particularly Bulk.find and update. As for adding unique values, you can use $addToSet

var bulk = db.items.initializeUnorderedBulkOp();
bulk.find({cell: socket.cell}).update({$addToSet: {sessions: id}});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM