Mongodb use findAndModify on specific document among multiple match

落花浮王杯 提交于 2019-12-13 04:14:05

问题


I have documents that look like below

let object = [
    {
        id: 4,
        parents:
            [
                1, 2,
            ],
        children: 2
    },
    {
        id: 5,
        parents:
            [
                1, 2,
            ],
        children: 1
    },
    {
        id: 8,
        parents:
            [
                1, 2, 4
            ],
        children: 0
    },
    {
        id: 9,
        parents:
            [
                1, 2, 4
            ],
        children: 0
    },
    {
        id: 10,
        parents:
            [
                1,2,5
            ],
        children:0
    }
]

I would like to use findAndModify in order to update the children value. It has to be findAndModify because I will be working in an multithreaded environment so selection and update must happen in single transaction.

The conditions that I am looking for is when '2' is included in the parents array and children value is less than 2 where the children value is highest and parents count is lowest among the sufficing documents. Then I would like to increment the value of children of the first matching document.

The query that I have come up with right now is below

let query =
    {
        parents:
            {
                $elemMatch:2
            },
        children:
            {
                $lt: 2
            }
    };

which suffices first few conditionals but unfortunately I don't know how I can select out

{
    id: 5,
    parents:
        [
            1, 2,
        ],
    children: 1
},

out of

{
    id: 8,
    parents:
        [
            1, 2, 4
        ],
    children: 0
},
{
    id: 9,
    parents:
        [
            1, 2, 4
        ],
    children: 0
},
{
    id: 10,
    parents:
        [
            1,2,5
        ],
    children:0
}

which is what is currently selected with my query. Again, it has to be a single transaction so writing out another set of query is not possible.

As to why it has to be single transaction, refer to this post How to limit maximum reference of the parental node in mongodb


回答1:


Try this

query.findAndModify({
    query: { $and: [ { children :{$lt : 2 }}, { parents: { $size: 2 } } ] },
    update: { according to you }
});


来源:https://stackoverflow.com/questions/48921005/mongodb-use-findandmodify-on-specific-document-among-multiple-match

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!