假设我有这个数组
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 :(得分: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']}}}
])