【问题标题】:Use aggregation to match one field of the document with the array size of that same document使用聚合将文档的一个字段与同一文档的数组大小相匹配
【发布时间】:2017-03-29 08:11:06
【问题描述】:

我正在使用带有 mongodb 的 nodejs,并且我的数据库中有以下文档

{
arr: ["abc", "def", "ghi", "jkl"],
ctr: 0
},
{
arr: ["aeiop"],
ctr: 0
}

现在我想编写一个聚合查询,如果 ctr 小于数组 arr 的大小,那么我想返回该文档。

下面是我写的查询

areamodel.aggregate(
            { $match : { ctr:{$lt : {$size: "$arr"} } },
            {$sort:{time_posted: -1}},
            function(err, docs) {
                if (err) {
                    console.log(err);
                } else {

                }
            }
        );

但我没有得到任何回应,因为没有任何查询匹配。

谁能告诉我在 mognodb 中如何执行聚合查询。

【问题讨论】:

    标签: node.js mongodb mongodb-query aggregation-framework


    【解决方案1】:

    考虑在 $project 管道和后续 $match 管道中操作 comparison operators,以使用 @ 根据附加字段过滤文档987654324@ 表达式:

    couponmodel.aggregate([
        {
            "$project": {
                "arr": 1,
                "ctr": 1,
                "time_posted": 1,
                "comparer": { 
                    "$cmp": [ "$ctr", { "$size": "$arr" } ]
                }
            }
        },
        { "$match": { "comparer": -1 } }
        { "$sort": { "time_posted": -1 } },
    ], function(err, docs) {
        if (err) {
            console.log(err);
        } else {
            console.log(docs);
        }
    });
    

    这种方法的唯一缺点是您需要投影所需的字段以及创建一个您可能不需要的附加字段。


    绕过上述情况的另一种选择是使用带有 $redact 运算符的单个管道,它结合了 $project$match 的功能strong> 如上所述,并使用 $$KEEP 系统变量返回与指定条件匹配的所有文档,并丢弃使用 $$PRUNE 系统变量不匹配的文档。请记住,此操作符会进行集合扫描,因此第一个管道选项可能是在适当的索引技术下是最佳的:

    couponmodel.aggregate([
        {
            "$redact": {
                "$cond": [
                    { 
                        "$eq": [
                            { "$cmp": [ "$ctr", { "$size": "$arr" } ] }, 
                            -1
                        ]
                    }, 
                    "$$KEEP", 
                    "$$PRUNE"
                ]
            }
        },
        { "$sort": { "time_posted": -1 } },
    ], function(err, docs) {
        if (err) {
            console.log(err);
        } else {
            console.log(docs);
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-11
      • 1970-01-01
      • 2015-08-19
      • 2018-01-25
      • 2021-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多