【问题标题】:Efficient way to find array elements not in mongodb查找不在 mongodb 中的数组元素的有效方法
【发布时间】:2017-01-05 06:47:41
【问题描述】:

假设我有这个数组

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?

【问题讨论】:

    标签: arrays mongodb meteor


    【解决方案1】:

    解决方案是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']}}}
    ])
    

    【讨论】:

      猜你喜欢
      • 2010-10-13
      • 2013-06-14
      • 1970-01-01
      • 1970-01-01
      • 2010-09-29
      • 2021-11-11
      • 2012-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多