【问题标题】:Projection with single child object带有单个子对象的投影
【发布时间】:2015-06-17 14:53:12
【问题描述】:

假设我有类似的东西:

{ "_id" : 1, "semester" : 1, "grades" : { student1: 70, student2: 85 }}
{ "_id" : 1, "semester" : 1, "grades" : { student1: 55, student2: 24 }}

我想做一个find(),在我的投影中我只想要student2,它是grades的子对象/属性

我的幼稚做法:

db.streets.find({dowhatever}, {_id:1, grades.student2: 1})

没用,所以我查看了http://docs.mongodb.org/manual/reference/operator/projection/,我想$slice 可能是我想要的,但似乎不是。

【问题讨论】:

    标签: mongodb projection


    【解决方案1】:

    您可以access fields inside an embedded document using the dot notation。不过不要忘记引用字段名称。

    > db.collection.find()
    { "_id" : 1, "semester" : 1, "grades" : { "student1" : 70, "student2" : 85 } }
    { "_id" : 2, "semester" : 2, "grades" : { "student1" : 55, "student2" : 24 } }
    
    > db.collection.find({_id: 2}, { "grades.student2": 1})
    { "_id" : 2, "grades" : { "student2" : 24 } }
    

    请注意,_id 是隐式投影的。您不必指定它,除非您想删除它 (_id: 0)。

    【讨论】:

    • 问题是我没有引用字段名称
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    相关资源
    最近更新 更多