Mongodb 在多个匹配中的特定文档上使用 findAndModify [英] Mongodb use findAndModify on specific document among multiple match

查看:58
本文介绍了Mongodb 在多个匹配中的特定文档上使用 findAndModify的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下所示的文档

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
    }
]

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

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.

我正在寻找的条件是当 parents 数组中包含 '2' 并且 children 值小于 2 时 children value 在足够的文档中最高,父计数最低.然后我想增加第一个匹配文档的孩子的价值.

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.

我现在提出的查询如下

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
},

{
    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.

至于为什么必须是单笔交易,请参考这篇文章如何限制mongodb中父节点的最大引用

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

推荐答案

试试这个

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

这篇关于Mongodb 在多个匹配中的特定文档上使用 findAndModify的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆