【问题标题】:Get back matched array elements present in a document's field which is also an array取回文档字段中存在的匹配数组元素,该字段也是一个数组
【发布时间】:2016-11-16 22:15:29
【问题描述】:

我有一个下面定义的数组,其中包含一些字符串,

arr = ["hola", "hii", "hey", "namaste"];

下面是 我在 mongodb 中的文档

{
    "user_id": "Michael",
    "list": ["hola", "ola", "hey", "maybe"]
}

现在我想在 mongodb 中编写一个查询,它返回所有“arr”元素,这些元素也存在于特定“user_id”的“列表”中。

所以我想要的输出是

_id: "_id" : ObjectId("5828ae4779f2e01b06bb7a61"), results: ["hola", "hey"]

我使用聚合在下面的查询中写了,但我收到错误

MongoError: FieldPath field names may not start with '$'

我的代码

arraymodel.aggregate(
        { $match: { user_id: "Michael" }},
        { $unwind: '$list'},
        { $match: {list: {$in: arr}}},
        { $group: {_id: '$_id', results: {$push: '$list.$'}}},
        function(err, docs) {
            if (err) {
                console.log('Error Finding query results');
                console.log(err);
            } else {
                if (docs) {
                    console.log('docs: ', docs);
                } else {
                    console.log('No Arr Found');
                }
            }
        }
        );

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    只需去掉{$push: '$list.$'} 中的$,你就会得到想要的输出。

    下面是完整的查询:

        db.collection.aggregate(
    {$match:{user_id:"Michael"}},
    {$unwind:'$list'},
    {$match:{list:{$in:["hola","hey"]}}},
    {$group:{_id:"$_id",results:{$push:"$list"}}})
    

    【讨论】:

    【解决方案2】:

    您可以为此尝试 $setIntersection。

    db.arrayModel.aggregate(
        [{
            $match: {
                user_id: "Michael"
            }
        }, {
            $project: {
                _id: 1,
                results: {
                    $setIntersection: ["$list", ["hola", "hii", "hey", "namaste"]]
                }
            }
        }]
    )
    

    样本输出

    { "_id" : ObjectId("582c6902a5ff9d6d50e722c3"), "results" : [ "hola", "hey" ] }
    

    【讨论】:

    • 抱歉,首先我接受了这个答案。
    • 另外你能帮帮我吗我还有一个关于聚合的问题stackoverflow.com/questions/40596317/…
    • 仅供参考,我先发布了答案。
    • 抱歉帖子是根据我现在接受的活跃度排序的,非常感谢:)
    • 你有什么收获吗??关于我上面问的问题??
    猜你喜欢
    • 2021-01-28
    • 2013-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 2022-10-31
    • 2020-10-16
    • 2017-01-10
    相关资源
    最近更新 更多