mongo 条件运算符中的成员资格测试
Membership testing in conditional operator in mongo
如何在 $cond
中使用 $in
(类似)运算符?例如,在 "project" 阶段中,我想创建一个名为 "category" 的新字段,该字段以其他一些字段为条件(用于稍后分组):如果 [=25,则其值为 catA
=] 在列表 [1,9] else "catB" 中。对于小列表,我可以在“$or”中使用一组 $eq
。
"category": {
"$cond": {
"if" :{
"$or" : [
{ "$eq" : ["$test_value", 1]},
{"$eq" : ["$test_value", 9] }
]
},
"then": {
"$literal" : "catA"
},
"else": {
"$literal" : "catB"
}
}
有没有办法使用类似的东西:
"if" :{
"$in" : {"$test_value", [1,9]}
},
"then": {
"$literal" : "catA"
},
"else": {
"$literal" : "catB"
}
}
我正在使用 mongoengine,上面的语法是不允许的。
您可以使用 $setIntersection 对该字段和该字段的预期值列表进行交集,并检查结果的长度。如果长度大于 0,则该字段具有预期值列表中的值。
尝试以下查询:
db.collection.aggregate([
{
$project: {
category: {
$let: {
vars: {
resultSize: {
$size: { $setIntersection: [["$test_value"], [1, 9]] }
}
},
in: {
"$cond": {
"if": { "$gt" : ["$$resultSize", 0] },
"then": { "$literal" : "catA" },
"else": { "$literal" : "catB" }
}
}
}
}
}
}
])
如何在 $cond
中使用 $in
(类似)运算符?例如,在 "project" 阶段中,我想创建一个名为 "category" 的新字段,该字段以其他一些字段为条件(用于稍后分组):如果 [=25,则其值为 catA
=] 在列表 [1,9] else "catB" 中。对于小列表,我可以在“$or”中使用一组 $eq
。
"category": {
"$cond": {
"if" :{
"$or" : [
{ "$eq" : ["$test_value", 1]},
{"$eq" : ["$test_value", 9] }
]
},
"then": {
"$literal" : "catA"
},
"else": {
"$literal" : "catB"
}
}
有没有办法使用类似的东西:
"if" :{
"$in" : {"$test_value", [1,9]}
},
"then": {
"$literal" : "catA"
},
"else": {
"$literal" : "catB"
}
}
我正在使用 mongoengine,上面的语法是不允许的。
您可以使用 $setIntersection 对该字段和该字段的预期值列表进行交集,并检查结果的长度。如果长度大于 0,则该字段具有预期值列表中的值。
尝试以下查询:
db.collection.aggregate([
{
$project: {
category: {
$let: {
vars: {
resultSize: {
$size: { $setIntersection: [["$test_value"], [1, 9]] }
}
},
in: {
"$cond": {
"if": { "$gt" : ["$$resultSize", 0] },
"then": { "$literal" : "catA" },
"else": { "$literal" : "catB" }
}
}
}
}
}
}
])