【问题标题】:MongoDB query only the inner documentMongoDB 只查询内部文档
【发布时间】:2014-03-27 11:31:42
【问题描述】:

我的 mongodb 集合如下所示:

 {
        "_id" : ObjectId("5333bf6b2988dc2230c9c924"),
        "name" : "Mongo2",
        "notes" : [
                {
                    "title" : "mongodb1",
                    "content" : "mongo content1"
                },
                {
                    "title" : "replicaset1",
                    "content" : "replca content1"
                }
        ]
    }
    {
        "_id" : ObjectId("5333fd402988dc2230c9c925"),
        "name" : "Mongo2",
        "notes" : [
                {
                    "title" : "mongodb2",
                    "content" : "mongo content2"
                },
                    {
                            "title" : "replicaset1",
                            "content" : "replca content1"
                    },
                    {
                            "title" : "mongodb2",
                            "content" : "mongo content3"
                    }
            ]
    }

我只想查询标题为“mongodb2”但不想要完整文档的笔记。 我正在使用以下查询:

 > db.test.find({ 'notes.title': 'mongodb2' }, {'notes.$': 1}).pretty()
    {
            "_id" : ObjectId("5333fd402988dc2230c9c925"),
            "notes" : [
                    {
                            "title" : "mongodb2",
                            "content" : "mongo bakwas2"
                    }
            ]
    }

我期待它返回标题为“mongodb2”的两个注释。 当我们在文档中查询文档时,mongo 是否只返回第一个文档?

【问题讨论】:

  • 这个问题已经在 StackOverflow 上被问过很多次了。查看上面的链接,例如:stackoverflow.com/questions/5562485/…。
  • 我发现很难理解这些问题,因为它们是从不存在聚合框架的时候开始的。这些问题之一的公认答案甚至是使用 map/reduce,这几乎肯定不是 OP 想要的,因为 M/R 不适合临时查询。

标签: mongodb aggregation-framework


【解决方案1】:

positional $ 运算符只能返回它找到的第一个匹配索引。

使用aggregate:

db.test.aggregate([

    // Match only the valid documents to narrow down
    { "$match": { "notes.title": "mongodb2" } },

    // Unwind the array
    { "$unwind": "$notes" },

    // Filter just the array
    { "$match": { "notes.title": "mongodb2" } },

    // Reform via group
    { "$group": {
        "_id": "$_id",
        "name": { "$first": "$name" },
        "notes": { "$push": "$notes" }
    }}       
])

因此您可以使用它来“过滤”数组中的特定文档。

【讨论】:

    【解决方案2】:

    $ 总是指第一个匹配项,$elemMatch 投影运算符也是如此。

    我认为你有三个选择:

    1. 将注释分开,这样每一个都是自己的文档
    2. 接受通过网络发送更多数据并过滤客户端
    3. 使用聚合管道($match 和 $project)

    我可能会选择选项 1,但您的数据模型可能有原因。

    【讨论】:

    • 我没有将笔记作为单独的文档分开,因为所有笔记都很少有会重复的共同值。如果我要在选项 2 和 3 之间进行选择,不确定哪一个会有更好的性能。还需要像使用 Spring-data 存储库一样考虑实现。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 2021-02-25
    • 2016-08-16
    相关资源
    最近更新 更多