首页 > 解决方案 > Mongodb IN和返回元素不匹配

问题描述

我有一个players这样的集合:

{    
 "_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_test

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

然后我想获取数组中不匹配的元素(不在 $nin 的集合中)。我的例子我需要输出:[43, 555]

像这样:(但我想知道是否可以通过一个查询):

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]

标签: javascriptmongodb

解决方案


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

首先,我们搜索玩家,然后创建他们的 id_test 数组,然后通过$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]

推荐阅读