I have this simple db, with subset of elements:
{ "_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"
}
]
}
when I execute a subset find:
db.photos.find({},{“comments.name”:1})
Im receive this structure:
[
{
"_id" : ObjectId("5019eb2356d80cd005000000"),
"comments" : [
{
"name" : "mike"
},
{
"name" : "pedro"
}
]
},
{
"_id" : ObjectId("5019eb4756d80cd005000001"),
"comments" : [
{
"name" : "luca"
},
{
"name" : "stef"
},
{
"name" : "joice"
}
]
}
]
But I want to get a simple one-dimensional array, like this(or similar):
[
{
"name" : "mike"
},
{
"name" : "pedro"
},
{
"name" : "luca"
},
{
"name" : "stef"
},
{
"name" : "joice"
}
]
I need to implement this query with mongo php official driver, but the language is not important, I just want to understand by what logic can I accomplish this by mongo shell
tnk!
The easiest option would be to use distinct():
Here’s another example using JavaScript:
Here’s an example using the new aggregation framework in the upcoming MongoDB 2.2: