gpt4 book ai didi

mongodb - 如何在子属性上使用 $setIsSubset(或其他设置操作)

转载 作者:可可西里 更新时间:2023-11-01 09:59:10 26 4
gpt4 key购买 nike

我遇到了一个我觉得非常简单的问题,我只是遗漏了一些东西,所以我希望有人能指出我哪里出错了。我正在尝试使用引用包含项目列表的子属性的 $setIsSubset 操作,但它告诉我它为空。基本上查询是错误的,但我不明白为什么。这是 Mongo shell 的输出:

$ mongo setTest
MongoDB shell version: 2.6.3
connecting to: setTest
> db.items.insert({"credentials":{"authorities":["AUTH1"]}});
WriteResult({ "nInserted" : 1 })
> db.items.find();
{ "_id" : ObjectId("53acd0e214c4ee1272550de4"), "credentials" : { "authorities" : [ "AUTH1" ] } }
> var userAuthorities = ["AUTH1","AUTH2","AUTH3"];
> db.items.aggregate([
... { $redact:
... {
... $cond:
... {
... if: { $setIsSubset: ["$credentials.authorities", userAuthorities ] },
... then: "$$DESCEND",
... else: "$$PRUNE"
... }
... }
... }
... ]);
assert: command failed: {
"errmsg" : "exception: both operands of $setIsSubset must be arrays. First argument is of type: EOO",
"code" : 17310,
"ok" : 0
} : aggregate failed
Error: command failed: {
"errmsg" : "exception: both operands of $setIsSubset must be arrays. First argument is of type: EOO",
"code" : 17310,
"ok" : 0
} : aggregate failed
at Error (<anonymous>)
at doassert (src/mongo/shell/assert.js:11:14)
at Function.assert.commandWorked (src/mongo/shell/assert.js:244:5)
at DBCollection.aggregate (src/mongo/shell/collection.js:1149:12)
at (shell):1:10
2014-06-26T20:04:54.465-0600 Error: command failed: {
"errmsg" : "exception: both operands of $setIsSubset must be arrays. First argument is of type: EOO",
"code" : 17310,
"ok" : 0
} : aggregate failed at src/mongo/shell/assert.js:13
>

谁能看出我做错了什么?

最佳答案

这里的问题不在于 set operators自己但以你的理解$redact .

$redact管道阶段递归遍历文档以测试字段值,因此这里的问题是您引用要匹配的数组的方式实际上并不总是出现在“当前深度”。

您有几种方法可以解决这个问题。要么首先使用 $project 操作以确保阵列存在于所有深度。 :

var userAuthorities = ["AUTH1","AUTH2","AUTH3"];

db.items.aggregate([
{ "$project": {
"credentials": 1,
"authorities": { "$literal": [] }
}},
{ "$redact": {
"$cond": {
"if": { "$setIsSubset": [ "$authorities", userAuthorities ] },
"then": "$$DESCEND",
"else": "$$PRUNE"
}
}}
])

或者测试该字段是否存在,并通过 $ifNull 替换为空数组:

db.items.aggregate([
{ "$redact": {
"$cond": {
"if": {
"$setIsSubset": [
{ "$ifNull": [ "$authorities", { "$literal": [] } ]},
userAuthorities
]
},
"then": "$$DESCEND",
"else": "$$PRUNE"
}
}}
])

或者最后总是接受你正在使用 $$ROOT比较。但是有点违背了 $redact 的目的

db.items.aggregate([
{ "$redact": {
"$cond": {
"if": {
"$setIsSubset": [
"$$ROOT.credentials.authories"
userAuthorities
]
},
"then": "$$DESCEND",
"else": "$$PRUNE"
}
}}
])

但基本上来说,与$redact 的比较是相对于当前下降到的文档的级别。因此,您的变量比较也必须考虑到这一点。

关于mongodb - 如何在子属性上使用 $setIsSubset(或其他设置操作),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24442948/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com