我有这个简单的数据库,包含元素的子集:
{ "_id" : ObjectId("5019eb2356d80cd005000000"),
"photo" : "/pub/photos/file1.jpg",
"comments" : [
{
"name" : "mike",
"message" : "hello to all"
},
{
"name" : "pedro",
"message" : "hola a todos"
}
]
},
{ "_id" : ObjectId("5019eb4756d80cd005000001"),
"photo" : "/pub/photos/file2.jpg",
"comments" : [
{
"name" : "luca",
"message" : "ciao a tutti"
},
{
"name" : "stef",
"message" : "todos bien"
},
{
"name" : "joice",
"message" : "vamos a las playa"
}
]
}
当我执行子集查找时: db.photos.find({},{"comments.name":1})
我收到这个结构:
[
{
"_id" : ObjectId("5019eb2356d80cd005000000"),
"comments" : [
{
"name" : "mike"
},
{
"name" : "pedro"
}
]
},
{
"_id" : ObjectId("5019eb4756d80cd005000001"),
"comments" : [
{
"name" : "luca"
},
{
"name" : "stef"
},
{
"name" : "joice"
}
]
}
]
但我想得到一个简单的一维数组,像这样(或类似的):
[
{
"name" : "mike"
},
{
"name" : "pedro"
},
{
"name" : "luca"
},
{
"name" : "stef"
},
{
"name" : "joice"
}
]
我需要用mongo php官方驱动来实现这个查询,但是语言并不重要,我只是想了解mongo shell通过什么逻辑可以完成这个
天啊!
最佳答案
最简单的选择是使用 distinct() :
>db.photos.distinct("comments.name");
[ "mike", "pedro", "joice", "luca", "stef" ]
这是另一个使用 JavaScript 的例子:
// Array to save results
> var names = []
// Find comments and save names
> db.photos.find({},{"comments.name":1}).forEach(
function(doc) { doc.comments.forEach(
function(comment) {names.push(comment.name)})
})
// Check the results
> names
[ "mike", "pedro", "luca", "stef", "joice" ]
下面是一个在即将推出的 MongoDB 2.2 中使用新聚合框架的示例:
db.photos.aggregate(
{ $unwind : "$comments" },
{ $group : {
_id: "names",
names: { $addToSet : "$comments.name" }
}},
{ $project : {
'_id' : 0,
'names' : 1,
}}
)
关于mongodb序列化子集结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11770590/