[英]How to use Mongodb if condition in $and operator
I am working on MongoDB and next js project.我正在研究 MongoDB 和下一个 js 项目。 I want to apply filter on products.我想对产品应用过滤器。 There are multiple filters.有多个过滤器。 I want to include a filter in and operator only if value of a variable is not empty or undefined I want something like this that works仅当变量的值不为空或未定义时,我才想在 and 运算符中包含过滤器我想要这样的东西
Product.find({
$and:[
{ tag : { $in : preferences,},
{$cond:{
if: { $ne: ['$allergens'], []],},
then: {
allergens: {$in :allergens },
if:{ $ne: ['$type'],''],},
then: {
type: type ,
}
}
})
}]
What would be the correct way of doing this?这样做的正确方法是什么? Thanks谢谢
Check the correct syntax:检查正确的语法:
{ $and: [ { Expression1 }, { Expression2 }, ..., { ExpressionN } ] }
or
{ { Expression1 }, { Expression2 }, ..., { ExpressionN }}
This should work.这应该有效。 The trick is to use $cond
plus $ifNull
to see if the field is unset.诀窍是使用$cond
加上$ifNull
来查看该字段是否未设置。
var r = [
{ tag: [ "A","B"], allergens: ["pollen","badJokes"], type: "foo" },
{ tag: [ "B","C"], type: "foo" },
{ tag: [ "C","D"], allergens: ["other"] },
{ tag: [ "E","D"], allergens: ["corn"] }
];
db.foo.drop();
db.foo.insert(r);
var tags = [ "C","A" ];
var type = 'foo';
var allergens = ['pollen','corn'];
c = db.foo.aggregate([
{$match: {$expr: {$and: [
{$ne:[ [], {$setIntersection: [ "$tag", tags ]} ] },
{$cond: {
if: {$eq:["$type", {$ifNull:["$type",null]} ]},
then: {$eq:["$type",type]},
else: true
}},
{$cond: {
if: {$eq:["$allergens", {$ifNull:["$allergens",null]} ]},
then: {$gt:[{$size: {$setIntersection: [ "$allergens", allergens ]}} , 0 ]},
else: true
}}
]}
}}
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.