我有一個包含以下檔案的集合
{
"_id" : ObjectId("4e8ae86d08101908e1000001"),
"food" : ["Apples", "Banana", "Grapes", "Pear"],
}
我如何構造一個聚合,它將回傳與陣列匹配的元素的索引,即
認為
array = ["Apples", "Grapes"]
我如何獲得以下內容
indexes: [0, 2]
我知道 $indexOfArray 回傳與搜索運算式匹配的元素第一次出現的索引,但是有沒有辦法使用它以便我可以用它構造一個索引陣列?
uj5u.com熱心網友回復:
$match$unwind$match$group
db.collection.aggregate([
{
"$match": {
"food": {
$in: [
"Apples",
"Grapes"
]
}
}
},
{
$unwind: {
path: "$food",
includeArrayIndex: "index"
}
},
{
"$match": {
"food": {
$in: [
"Apples",
"Grapes"
]
}
}
},
{
"$group": {
"_id": "$_id",
"index": {
"$push": {
"$toInt": "$$ROOT.index"
}
}
}
}
])
mongoplayground
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/378789.html
