我有这样的文件:
{
"_id" : ObjectId("5d302a6da9b1d6ae926c16a3"),
"location" : "car",
"playlist" : [
{
"playlist_number" : "1",
"number_of_songs" : "100",
"drive" : [
{
"drive_number" : "13",
"drive_name" : "Ooms",
"songs" : [
"59 Volvo",
"Yield Not To Temptation - Single Version",
"Johnny Angel",
"The Madison Time",
"Little Brown Jug",
"Only In My Dreams"
]
},
{
"drive_number" : "Z3",
"drive_name" : "codes",
"songs" : [
"59 Volvo",
"Perfect",
"Hands clap",
"I Ran",
"Falling down",
"Sounds of middle earth"
]
}
]
}
]
}
可能还有许多其他location
,它们可能包含数量可变的playlist
个对象(而对象又可以包含n
个数量的playlist_number
,您会发现)。
当我按名称搜索歌曲时,例如:59 Volvo
,我应该返回location
,playlist_number
,drive_number
和drive_name
。我尝试使用嵌套的$elemMatch
,但它给出了整个文档。
答案 0 :(得分:0)
在运行$unwind之前,您需要$match数据。然后,您可以使用$project重塑数据。另外,您可以添加一个$match
作为第一步,以便在进一步处理之前过滤掉不必要的文档:
db.collection.aggregate([
{
$match: { "playlist.drive.songs": "59 Volvo" }
},
{
$unwind: "$playlist"
},
{
$unwind: "$playlist.drive"
},
{
$match: { "playlist.drive.songs": "59 Volvo" }
},
{
$project: {
location: 1,
drive_number: "$playlist.drive.drive_number",
drive_name: "$playlist.drive.drive_name",
playlist_number: "$playlist.playlist_number",
}
}
])