我有以下代碼:
const array = ['a', 'b', 'c']
await collection.aggregate([
{
$match: {
codes: { $in: array }
}
},
{
$addFields: { matchedField: "codes.$" } // <--- does not work
},
]).toArray();
我需要將陣列中匹配的元素附加到回傳的結果中。有可能這樣做嗎?
我的收藏包含具有以下方案的檔案:
{
"color": "red",
"codes": [ "b" ]
}
我需要聚合指令來回傳這個:
{
"color": "red",
"codes": [ "b" ],
"matchedField": "b",
}
uj5u.com熱心網友回復:
$filter
db.collection.aggregate([
{
"$match": {
"codes": {
"$in": [
"a",
"b",
"c"
]
}
}
},
{
"$set": {
codes: {
$filter: {
input: "$codes",
as: "c",
cond: {
$in: [
"$$c",
[
"a",
"b",
"c"
]
]
}
}
}
}
}
])
mongoplayground
$setIntersection
db.collection.aggregate([
{
"$match": {
"codes": {
"$in": [
"a",
"b",
"c"
]
}
}
},
{
"$set": {
codes: {
$setIntersection: [
"$codes",
[
"a",
"b",
"c"
]
]
}
}
}
])
mongoplayground
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/344964.html
上一篇:在MongoDB和Cassandra等NoSQL資料庫中,對可以包含相同型別屬性陣列的資源進行建模的正確方法是什么?
