简体   繁体   English

Mongodb找到并插入

[英]Mongodb find and insert

I would like to: 我想要:

1) find documents 1)找到文件

2) each of the found documents include an array, I would like to insert a new array element into the array. 2)每个找到的文件都包含一个数组,我想在数组中插入一个新的数组元素。 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. 您可以使用批量操作,尤其是Bulk.find和更新。 As for adding unique values, you can use $addToSet 至于添加唯一值,您可以使用$addToSet

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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