2017-01-04 29 views
0

让说我有这个数组有效的方式来找到MongoDB中的数组元素不

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的方法吗?

回答

0

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

要获得数组内所有实体的集合,我们可以使用$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']}}} 
]) 
相关问题