您需要使用聚合和设置(仅唯一值)
查询:
db.getCollection('movies')
.aggregate([
// optionaly filter records to apply on
//{
// $match: { email: /rambo/ }
//},
{
$project: { // project values you want to see in result
// record id is present by default
email: "$email",
genres: { // brand new field with desired output
$reduce: { // reduce like Array.reduce in javascript
input: "$movies_watched", // array to reduce
initialValue: [],
in: {
$setUnion: // the function doing the magic
// if you use $concatArrays instead - it will contain duplicities
[
"$$value", // destination in initialValue
"$$this.movie_genres" // field to take items from
]
}
}
}
}
}
])
结果:
[
{
"_id": {"$oid": "60a7c3d23541f3714eb91332"},
"email": "rambo@hotmail.com",
"genres": [18, 28, 53]
},
{
"_id": {"$oid": "60a7c4373541f3714eb9135f"},
"email": "dexter@hotmail.com",
"genres": [13, 18, 28, 53]
}
]
数据集:
[
{
"_id" : ObjectId("60a7c3d23541f3714eb91332"),
"email" : "rambo@hotmail.com",
"password" : "12345",
"movies_watched" : [
{
"title" : "Rambo",
"movie_id" : 7555,
"movie_runtime" : 99,
"movie_genres" : [
28,
53
]
},
{
"title" : "Rambo: Last Blood",
"movie_id" : 522938,
"movie_runtime" : 99,
"movie_genres" : [
28,
53,
18
]
}
]
},
{
"_id" : ObjectId("60a7c4373541f3714eb9135f"),
"email" : "dexter@hotmail.com",
"password" : "123456",
"movies_watched" : [
{
"title" : "Dexter",
"movie_id" : 444,
"movie_runtime" : 99,
"movie_genres" : [
13,
18
]
},
{
"title" : "Rambo: Last Blood",
"movie_id" : 522938,
"movie_runtime" : 99,
"movie_genres" : [
28,
53,
18
]
}
]
}
]