Mongodb在多个匹配中的特定文档上使用findAndModify

时间:2022-02-05 02:32:51

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.

我想使用findAndModify来更新子值。它必须是findAndModify,因为我将在多线程环境中工作,因此选择和更新必须在单个事务中进行。

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.

我正在寻找的条件是,父母数组中包含“2”,子元素值小于2,其中子元素值最高,父母数量最少。然后我想增加第一个匹配文档的子项的值。

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

至于为什么它必须是单个事务,请参阅这篇文章如何限制mongodb中父节点的最大引用

1 个解决方案

#1


0  

Try this

尝试这个

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

#1


0  

Try this

尝试这个

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