仅返回mongo投影中的数组值

时间:2013-02-05 16:08:52

标签: mongodb

有没有办法只返回mongodb投影中的属性值?例如,我有一个文件,其属性值为数组。我希望查询中的返回对象只是数组,而不是property: [ .. ]。例如:

文件:

db.test.insert({ name: "Andrew",
   attributes: [ { title: "Happy"},
                 { title: "Sad" }
               ]
});

查询:

db.test.find({name: "Andrew"},{attributes:1, "_id":0});

返回:

{ "attributes" : [ { "title" : "Happy" }, { "title" : "Sad" } ] }

我希望它返回数组:

[ { title: "Happy"},
  { title: "Sad" }
]

有办法吗?感谢

1 个答案:

答案 0 :(得分:5)

JSON不允许顶层为数组,因此普通查询不允许这样做。但是,您可以使用聚合框架执行此操作:

> db.test.remove();
> db.test.insert({ name: "Andrew", attributes: [ { title: "Happy"}, { title: "Sad" } ] });
> foo = db.test.aggregate( { $match: { name: "Andrew" } }, { $unwind: "$attributes" }, { $project: { _id: 0, title: "$attributes.title" } } );
{
    "result" : [
        {
            "title" : "Happy"
        },
        {
            "title" : "Sad"
        }
    ],
    "ok" : 1
}
> foo.result
[ { "title" : "Happy" }, { "title" : "Sad" } ]

然而,这并不会创建一个找到的游标对象。