找到不在mongodb中的数组元素的有效方法

时间:2017-01-04 21:53:36

标签: arrays mongodb meteor

假设我有这个数组

const testItems = ['a', 'b', 'c'];

和mongodb集合,如

const Cart = new Meteor.Collection('cart');
//{
//  _id: String,
//  items: [String]
//}

检查该集合中任何数组testItems的任何记录中items的哪些元素不属于哪种有效方法?

我天真的方式是通过迭代

const missingItems = testItems.filter(item => !Cart.findOne({ 'items': item }));

但有没有一种方法需要更少的I / O?

1 个答案:

答案 0 :(得分:0)

解决方案是testItems集与testItemsitems中所有实体集合的交集之间的差异。

要获取数组中所有实体的集合,我们可以使用$unwind操作,然后使用$group。为了计算集合之间的差异,可以使用$setDifference

Cart.aggregate([
{$unwind: '$items'},
{$group: {_id: '$items'}},
{$match: {_id: {$in: ['a', 'b', 'c']}}},
{$group: {_id: null, set: {$push: '$_id'}}},
{$project: {_id: 0, ans: {$setDifference: [['a', 'b', 'c'], '$set']}}}
])
相关问题