【问题标题】:MongoDB query for a specific field for each document?MongoDB查询每个文档的特定字段?
【发布时间】:2014-10-12 20:25:08
【问题描述】:

假设我的用户集合中有 2 个用户:

id: "1",
outer: {
    field1: {
        inner1: {
            a: cats
            b: car
        }
    }
}

id: "2",
outer: {
    field1: {
        inner1: {
            a: dogs
            b: bus
        }
    }
}

假设我有 10 个用户。我想为我的数据库中的每个用户获取字段“a”的值。如何进行此查询(在 mongo shell 中)?

【问题讨论】:

  • 我觉得你得用聚合函数来实现

标签: mongodb


【解决方案1】:
db.user.find({'field1.a': { $exists: true }, { 'field1.a': 1 });

编辑:如 cmets 中所述,您也可以使用聚合框架执行 project

db.user.aggregate({ $project: { a: '$field1.inner1.a' } });

【讨论】:

  • 你认为它会起作用吗,因为 field1 是 user1 文档的嵌套子文档。
  • 那么,user1user2 都是嵌入文档,而不是它们自己的顶级文档?
  • 我猜是这样...但@yimmy 可以确认。
  • 是的! field1嵌套在user1/user2中,a嵌套在field1中
  • 对不起各位!我刚刚意识到我的情况是还有一个嵌套的东西。我编辑了上面的对象
【解决方案2】:

对象的嵌套程度无关紧要,只需使用dot notation。我在下面写了一个例子。您的文件不完整且格式错误,有很多不同的方面,所以我冒昧地完成了它们,同时尝试匹配我认为您希望它们看起来像的样子。

> db.nested.insert([
{
    "_id" : "1",
    "outer" : {
        "field1" : {
            "inner1" : {
                "a" : "cats",
                "b" : "car"
            }
        }
    }
},
{
    "_id" : "2",
    "outer" : {
        "field1" : {
            "inner1" : {
                "a" : "dogs",
                "b" : "bus"
            }
        }
    }
}])
> db.nested.find({}, { "_id" : 0, "outer.field1.inner1.a" : 1 })
{ "outer" : { "field1" : { "inner1" : { "a" : "cats" } } } }
{ "outer" : { "field1" : { "inner1" : { "a" : "dogs" } } } }

选择文档字段的子集称为projection

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-24
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    相关资源
    最近更新 更多