我想使用管道通过过滤对象中子文档的键来更新文档。
例如数据:
{
things: {
a1: {},
...
x1: {}
}
}
“事物”可以包含变量键/属性。 我知道我可以使用这样的更新管道,其中“keepKeys”是我想保留在“things”对象中的键:
[
$set: {
things: {
$arrayToObject: {
$filter: {
"input": {
$objectToArray: "$$ROOT.things"
},
"as": "item",
"cond": {
"$in": [
"$$item.k",
keepKeys
]
}
}
}
}
]
这可行,但我宁愿过滤掉我不想要的东西,因为这是一个更短的列表,例如,其中discardKeys是我不想要的键:
[
$set: {
things: {
$arrayToObject: {
$filter: {
"input": {
$objectToArray: "$$ROOT.things"
},
"as": "item",
"cond": {
"$nin": [
"$$item.k",
discardKeys
]
}
}
}
}
]
但是管道$filter cond不支持$nin
$indexOfArray
来检查discardKeys中的密钥是否不存在。因为当未找到元素时 $indexOfArray
返回 -1
。
所以如果
discardKeys = ["x1", "x2", "a3" ]
:
db.collection.aggregate([
{
$set: {
things: {
$arrayToObject: {
$filter: {
"input": {
$objectToArray: "$$ROOT.things"
},
"as": "item",
"cond": {
$eq: [
{ $indexOfArray: [["x1", "x2", "a3"], "$$item.k"] },
-1
]
}
}
}
}
}
}
])