简体   繁体   中英

Mongodb IN and return elements not matched

I have a collection of players like this:

{    
 "_id": ObjectId("5eb93f8efd259cd7fbf49d55"),
 "id_test": 132
 "name": "John Doe"
},
{
 "_id": ObjectId("5eb93f8efd259cd7fbf49d33"),
 "id_test": 90
 "name": "Tom White"
},
{
 "_id": ObjectId("5eb93f8efd259cd7fbf49d31"),
 "id_test": 999
 "name": "Mike Barry"
}

I have an array of Ids with id_test :

const arrayIds = [ 132, 43, 90, 555];

Then I want to get elements not matched in array (not in collection with $nin). Im my example I need to output: [43, 555]

Something like this: (but I want to know if it's possible with one single query):

const players = await db.collection('players').find(
    { id_test: { "$in": arrayIds } } )
  .toArray();

const playersIds = players.map(e => e.id_test); // [132, 90]

const final = arrayIds.filter(i => !playersIds.includes(i)) // [43, 555]

Yes, you can do that in a single query by aggregation,

First, we search the players, then create an array of their id_test, then by $setDifference get the difference you want

const players = await db.collection('players').aggregate(
    [ { $match : 
        { 
            id_test : { "$in": arrayIds  } 
        } 
    },
    {
       $group:
         {
           _id: null,
           id_test: { $push:  "$id_test" }
         }
     },
     { $project: { final:{ $setDifference: [ arrayIds , "$id_test" ] }, _id: 0 } }
    ]
);

const final = players.final // [43, 555]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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