繁体   English   中英

Mongodb IN 和返回元素不匹配

[英]Mongodb IN and return elements not matched

我有一个这样的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_test的 ID 数组:

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

然后我想获取数组中不匹配的元素(不在 $nin 的集合中)。 我的例子我需要 output: [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]

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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