Given a list of ids, what's the best way to query which ids do not exist in the collection?

前端 未结 3 1508
轮回少年
轮回少年 2020-12-07 03:11

I have a collection of documents which contain unique id field. Now I have a list of ids which may contain some ids that do not exist in the collection. What\'s the best way

3条回答
  •  死守一世寂寞
    2020-12-07 03:35

    I suppose you have the following documents in your collection:

    { "_id" : ObjectId("55b725fd7279ca22edb618bb"), "id" : 1 }
    { "_id" : ObjectId("55b725fd7279ca22edb618bc"), "id" : 2 }
    { "_id" : ObjectId("55b725fd7279ca22edb618bd"), "id" : 3 }
    { "_id" : ObjectId("55b725fd7279ca22edb618be"), "id" : 4 }
    { "_id" : ObjectId("55b725fd7279ca22edb618bf"), "id" : 5 }
    { "_id" : ObjectId("55b725fd7279ca22edb618c0"), "id" : 6 }
    

    and the following list of id

    var listId = [ 1, 3, 7, 9, 8, 35 ];
    

    We can use the .filter method to return the array of ids that is not in your collection.

    var result = listId.filter(function(el){
        return db.collection.distinct('id').indexOf(el) == -1; });
    

    This yields

    [ 7, 9, 8, 35 ] 
    

    Now you can also use the aggregation frameworks and the $setDifference operator.

    db.collection.aggregate([
       { "$group": { "_id": null, "ids": { "$addToSet": "$id" }}}, 
       { "$project" : { "missingIds": { "$setDifference": [ listId, "$ids" ]}, "_id": 0 }}
    ])
    

    This yields:

    { "missingIds" : [ 7, 9, 8, 35 ] }
    

提交回复
热议问题