查询Mongodb的子文档

时间:2015-02-13 19:07:23

标签: mongodb aggregation-framework nosql

我有mongodb文档,格式如下

{
    inner : [{
        name : "I don't this",
        anotherName: "I don't want this",
        wayInside : [{
            something : 'skip this',
            somethingElse : 'skip this',
            someArray: { 
                 stuff:'I want this',
                 morestuff: {
                   field3: "Show me",
                   field2: "Show me",
                   field3: [{ "show everything from here down" }]
            }
        }]
    }]
}

我希望得到wayInside中的第一条记录

result: [{ 
                 stuff:'I want this',
                 morestuff: {
                   field3: "Show me",
                   field2: "Show me",
                   field3: [{ show everything from here down }]
 }]

我不希望在morestuff属性上面的属性中匹配任何我只想要moreStuff中的所有数据和一个字段(在本例中为“stuff”)。我该怎么做?

我已经尝试过聚合并找到...但是甚至没有接近......

2 个答案:

答案 0 :(得分:3)

使用aggregation pipeline

db.test.aggregate([
    {$unwind: "$inner"},
    {$unwind: "$inner.wayInside"},
    {$project: {
        stuff: "$inner.wayInside.someArray.stuff", 
        morestuff: "$inner.wayInside.someArray.morestuff"
    }}, 
    {$project: {stuff: 1, morestuff: 1, _id: 0}}
])

输出

{ 
    "stuff" : "I want this", 
    "morestuff" : { 
        "field3" : [ "show everything from here down" ],     
        "field2" : "Show me" 
    } 
}

答案 1 :(得分:0)

我认为您正在寻找的是MongoDB shell中的投影参数,该参数也可以在其特定于平台的驱动程序中使用。

http://docs.mongodb.org/manual/reference/method/db.collection.find/

所以你会想要这样的东西:

db.inner.find({
    "name": "I want this"
}, {
    "name": true,
    "wayInside": true
});