问题
I have a mongoose schema like -
db.foo.insert({one:'a',friends:[{two:'b',three:'c'},{two:'d',three:'e'},{two:'f',three:'G'}]})
now what i want is two retrieve only the 'two'
part of friends
array
that is I want to find an array of all the values of two
in each object in friends
array
Is such a projection possible in mongodb where in the output looks like -
['b','d','f']
回答1:
aggregate
is your answer
db.foo.aggregate({"$project" : {"two" : "$friends.two"}}).result
there is another way to do that (getting distinct values)
db.foo.aggregate([
{'$project': {
union:{$setUnion:["$friends.two"]}
}
}
]).result;
回答2:
You can do this with distinct:
db.foo.distinct('friends.two')
Output:
[
"b",
"d",
"f"
]
来源:https://stackoverflow.com/questions/27606591/how-to-retrieve-partial-objects-from-object-array-in-a-field-in-mongodb