Javascript Mongodb IN和返回元素不匹配

Javascript Mongodb IN和返回元素不匹配,javascript,mongodb,Javascript,Mongodb,我有一批玩家如下: { "_id": ObjectId("5eb93f8efd259cd7fbf49d55"), "id_test": 132 "name": "John Doe" }, { "_id": ObjectId("5eb93f8efd259cd7fbf49d33"), "id_test": 90 "name": "Tom White" }, { "_id": ObjectId("5eb93f8efd259cd7fbf49d31"), "id_test": 99

我有一批
玩家
如下:

{    
 "_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"
}
我有一个id数组,带有
id\u test

const arrayIds = [ 132, 43, 90, 555];
然后我想得到数组中不匹配的元素(不在$nin的集合中)。我需要输出我的示例:
[43555]

类似这样的:(但我想知道一个查询是否可行):


是的,您可以通过聚合在单个查询中执行此操作

首先,我们搜索玩家,然后创建他们id_测试的数组,然后通过$setDifference获得你想要的差异

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]

是的,您可以通过聚合在单个查询中执行此操作

首先,我们搜索玩家,然后创建他们id_测试的数组,然后通过$setDifference获得你想要的差异

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]