【问题标题】:Retrieve selected sub arrays with particular key value pair of a document in mongodb在 mongodb 中检索具有文档的特定键值对的选定子数组
【发布时间】:2014-03-09 10:19:15
【问题描述】:

我正在尝试检索满足特定条件的文档的子数组列表。

"_id" : "something",
"players" : [
    {
        "Name" : "Sunny"
        "score": 20
    },
    {
        "Name" : "John"
        "score" : 40
    },
    {
        "Name" : "Alice"
        "score" : 20
    },
    etc...
]

我想要分数 = 20 的输出,比如

{
    "Name" : "Sunny"
    "score": 20
},
{
    "Name" : "Alice"
    "score" : 20
}

但我尝试使用以下方式查询:

db.collection.find(
    { "players.score":20, "_id":"something" },
    { "players" :1 }
) 

但它给了我所有 3 个子数组,比如

{
    "Name" : "Sunny"
    "score": 20
},
{
    "Name" : "John"
    "score" : 40
},
{
     "Name" : "Alice"
    "score" : 20
}

如果我使用投影仪 "$" 或 $matchelement 比如:

db.collection.find({ "players.$.score":20, "_id":"something" }

它给出了第一个数组示例

{
    "Name" : "Sunny"
    "score": 20
}

谁能帮我正确查询这个。 在此先感谢:)

【问题讨论】:

    标签: php mongodb mongodb-query aggregation-framework


    【解决方案1】:

    是的,positional $ 运算符将匹配在匹配数组条件中找到的 first 元素。为了只过滤你想要的元素,使用aggregate

    db.collection.aggregate([
        // Uwinds the array (de-normalize)
        { "$unwind": "$players" },
    
        // Match just the elements you want
        { "$match": { "players.score": 20 } },
    
        // Push everything back into an array like it was        
        { "$group": { 
            "_id": "$_id",
            "players": { "$push": { 
                "name": "$players.name",
                "score": "$players.score"
            }} 
        }}
    ])
    

    如果您的文档有更多细节并且您也需要这些细节,请参阅here

    郑重声明,除了直接 dot . 表示法之外,您尝试的另一个运算符是 $elemMatch

    【讨论】:

    • @Aditya 如何复制代码您自己的答案?而且您发布的内容不会产生您在问题中要求的结果。 “我想要那些 score = 20 like 的输出”,列表是数组中的文档。这就是 $push 在这里所做的。让它展开并不是文档的状态。
    • @Aditya 虽然我可能应该在代码中检查数组正在正确重建。它现在通过编辑来完成。这里的正确做法是接受帮助你的人的回答。
    • 我实际上使用了您提供的相同查询,我没有改变任何东西。我想编辑以前的评论,但它允许我。
    • 我什至想为你的帖子投票,但我没有足够的代表这样做。
    • @Aditya 您可以接受并回答。当获得的知识对您有所帮助时,这是正确的做法。我相信这甚至会增加你的代表分数。如果不只是你名字的新徽章。
    猜你喜欢
    • 1970-01-01
    • 2015-02-13
    • 2021-12-12
    • 2021-05-26
    • 1970-01-01
    • 2016-05-16
    • 2015-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多