簡體   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