【问题标题】:MongoDB: find documents with a given array of subdocumentsMongoDB:查找具有给定子文档数组的文档
【发布时间】:2015-09-02 07:49:53
【问题描述】:

我想查找包含给定子文档的文档,假设我的 commits 集合中有以下文档:

// Document 1
{ 
  "commit": 1,
  "authors" : [
    {"name" : "Joe", "lastname" : "Doe"},
    {"name" : "Joe", "lastname" : "Doe"}
  ] 
}

// Document 2
{ 
  "commit": 2,
  "authors" : [
    {"name" : "Joe", "lastname" : "Doe"},
    {"name" : "John", "lastname" : "Smith"}
  ] 
}

// Document 3
{ 
  "commit": 3,
  "authors" : [
    {"name" : "Joe", "lastname" : "Doe"}
  ] 
}

我想要从上述集合中获得的只是第一个文档,因为我知道我正在寻找带有 2 个 authorscommit,它们都具有相同的 namelastname。所以我想出了这个查询: db.commits.find({ $and: [{'authors': {$elemMatch: {'name': 'Joe, 'lastname': 'Doe'}}, {'authors': {$elemMatch: {'name': 'Joe, 'lastname': 'Doe'}}], 'authors': { $size: 2 } })

$size 用于过滤掉第三个文档,但查询仍然返回第二个文档,因为 $elemMatch 都返回 True。

我不能对子文档使用索引,因为用于搜索的作者顺序是随机的。有没有办法在不使用 Mongo 的聚合函数的情况下从结果中删除第二个文档?

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    您在此处询问的内容与标准查询略有不同。实际上,您是在询问“姓名”和“姓氏”在您的数组中该组合中的位置 两次 次或更多次以识别该文档。

    标准查询参数与结果中的数组元素匹配“多少次”不匹配。当然,您可以使用aggregation framework 要求服务器为您“计数”:

    db.collection.aggregate([
        // Match possible documents to reduce the pipeline
        { "$match": {
            "authors": { "$elemMatch": { "name": "Joe", "lastname": "Doe" } }
        }},
    
        // Unwind the array elements for processing
        { "$unwind": "$authors" },
    
        // Group back and "count" the matching elements
        { "$group": {
            "_id": "$_id",
            "commit": { "$first": "$commit" },
            "authors": { "$push": "$authors" },
            "count": { "$sum": {
                "$cond": [
                    { "$and": [
                        { "$eq": [ "$authors.name", "Joe" ] },
                        { "$eq": [ "$authors.lastname", "Doe" ] }
                    ]},
                    1,
                    0
                ]
            }}
        }},
    
        // Filter out anything that didn't match at least twice
        { "$match": { "count": { "$gte": 2 } } }
    ])
    

    所以本质上是你,但你的条件要在 $cond 运算符中匹配,它在匹配的地方返回 1,在不匹配的地方返回 0,并将其传递给 $sum 以获得文档的总数。

    然后过滤掉任何不匹配 2 次或更多次的文档

    【讨论】:

    • 那么我将进行聚合 - 感谢您的时间!
    猜你喜欢
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    相关资源
    最近更新 更多