In mongodb know index of array element matched with $in operator?

后端 未结 3 1677
别那么骄傲
别那么骄傲 2020-12-11 12:19

I am using aggregation with mongoDB now i am facing a problem here, i am trying to match my documents which are present in my input array by using $in operator. Now i want t

相关标签:
3条回答
  • 2020-12-11 12:54

    So say we have the following in the database collection:

    > db.couponmodel.find()
    { "_id" : "a" }
    { "_id" : "b" }
    { "_id" : "c" }
    { "_id" : "d" }
    

    and we wish to search for the following ids in the collections

    var coupons_ids = ["c", "a" ,"z"];
    

    We'll then have to build up a dynamic projection state so that we can project the correct indexes, so we'll have to map each id to its corresponding index

    var conditions = coupons_ids.map(function(value, index){
        return { $cond: { if: { $eq: ['$_id', value] }, then: index, else: -1 } };
    });
    

    Then we can then inject this in to our aggregation pipeline

    db.couponmodel.aggregate([
        { $match : { '_id' : { $in : coupons_ids } } },
        { $project: { indexes : conditions } },
        { $project: {
            index : {
                $filter: { 
                    input: "$indexes", as: "indexes", cond: { $ne: [ "$$indexes", -1 ] }
                    }
                }
            } 
        },
        { $unwind: '$index' }
    ]);
    

    Running the above will now output each _id and it's corresponding index within the coupons_ids array

    { "_id" : "a", "index" : 1 }
    { "_id" : "c", "index" : 0 }
    

    However we can also add more items in to the pipeline at the end and reference $index to get the current matched index.

    0 讨论(0)
  • 2020-12-11 13:17

    I think you could do it in a faster way simply retrieving the array and search manually. Remember that aggregation don't give you performance.

    0 讨论(0)
  • 2020-12-11 13:17

    //$match,$in,$and

        $match:{
            $and:[        
            {"uniqueID":{$in:["CONV0001"]}},
            {"parentID":{$in:["null"]}},
            ]
           }
       }])
    
    0 讨论(0)
提交回复
热议问题