繁体   English   中英

如果条件在 $and 运算符中,如何使用 Mongodb

[英]How to use Mongodb if condition in $and operator

我正在研究 MongoDB 和下一个 js 项目。 我想对产品应用过滤器。 有多个过滤器。 仅当变量的值不为空或未定义时,我才想在 and 运算符中包含过滤器我想要这样的东西

 Product.find({ 

    $and:[
        { tag : { $in : preferences,},
            {$cond:{
                if: { $ne: ['$allergens'], []],},
                then: { 
                    allergens: {$in :allergens },
                if:{ $ne: ['$type'],''],},
                then: { 
                    type: type ,
               }
            }
})
}]

这样做的正确方法是什么? 谢谢

检查正确的语法:

{ $and: [ { Expression1 }, { Expression2 }, ..., { ExpressionN } ] }
or
{ { Expression1 }, { Expression2 }, ..., { ExpressionN }}

这应该有效。 诀窍是使用$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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM