[英]project field in MongoDB with I don't know intermediates field name
{
"matchs":{
"aus":{
"won":[2019, 2020],
"lose":[2018, 2017]
},
"pak":{
"won":[2002, 2003, 2004],
"lose":[]
}
}
}
我想在每個國家選擇獲勝的比賽
像 $project 或 $match 條件中的 "match.*.won"
喜歡
db.collection.aggregate([{$match:{"matchs":{"*.won":{$exists:true}}}}])
輸出如:
[{"matchs":{"aus":{"won":[2019, 2020]},"pak":{"won":[2002, 2003, 2004]}}]
而不是過濾won
,刪除lose
會更快。 會是這個:
db.collection.aggregate([
{ $set: { matchs: { $objectToArray: "$matchs" } } },
{ $unset: "matchs.v.lose" },
{ $set: { matchs: { $arrayToObject: "$matchs" } } }
])
或者,如果您更喜歡$set
:
db.collection.aggregate([
{ $set: { matchs: { $objectToArray: "$matchs" } } },
{
$set: {
"matchs": {
$map: {
input: "$matchs",
in: { k: "$$this.k", v: {won: "$$this.v.won" } }
}
}
}
},
{ $set: { matchs: { $arrayToObject: "$matchs" } } }
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.