【问题标题】:Finding Sub-documents through dot notation in mongodb在mongodb中通过点符号查找子文档
【发布时间】:2016-05-26 16:10:57
【问题描述】:

为简单起见,我在下面有一个简化的集合结构。我无法查询配置文件字段下的特定子文档。

例如,我要查找子文档“profiles.Bernie”。是否有一个 find() 查询允许我只检索 Bernie 的文档(即 Bernie 的类别和 ID)?抱歉,如果这是重复的,但我无法找到满足下面这个集合结构方式的解决方案

{
        "_id" : ObjectId("56aec822ceb6e9dc23d32271"),
        "sm_user" : "user1",
        "profiles" : {
                "Bernie" : {
                        "category" : "Politics",
                        "id" : "bernie"
                },
                "Hilary" : {
                        "category" : "Politics",
                        "id" : "hilary"
                }
        }
}

【问题讨论】:

    标签: mongodb nested mongodb-query pymongo


    【解决方案1】:

    是的,您可以选择只获取Bernie 子树并抑制通常包含的_id

    db.test.find({},{ _id:0, "profiles.Bernie":1 })
    

    包括通往Bernie(又名profiles标签)的结构,但仅包含来自该子树的数据。

    如果不想保留结构,也可以使用聚合框架将Bernie投影到输出文档的根目录;

    db.test.aggregate([{$project: { _id:0, 'Bernie': "$profiles.Bernie"}}])
    

    【讨论】:

    • 太好了,我脑子里放了个屁。我忘记了投影参数。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-08
    • 2021-07-25
    • 2016-08-25
    • 2016-04-18
    • 1970-01-01
    • 2015-11-08
    • 1970-01-01
    相关资源
    最近更新 更多