Mongodb use findAndModify on specific document amo

2019-08-20 05:25发布

问题:

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