【问题标题】:Exclude items that aren't in my collection from a js array从 js 数组中排除不在我的集合中的项目
【发布时间】:2018-06-15 16:04:36
【问题描述】:

假设我有一个包含 10000 个文档的集合,如下所示:

{"_id": 1, "name": "aaa"}
{"_id": 1, "name": "bbb"}
{"_id": 2, "name": "ccc"}
...

现在前端用户提交一个包含 100 个名称的数组,如下所示:

myArray = ["name1", "name2", "name3", "name4", ... "name100"]

他想知道这 100 个名称中的哪些尚未在数据库中,因此我需要返回一个新数组,其中包含这 100 个名称减去可以在我的集合中找到的名称。我该怎么做?

我在 Node (npm mongodb) 中使用官方的 MongoDB 驱动程序。

我目前所做的是首先通过执行 db.collection.find({name: {$in: myArray}}) 查找数据库中的名称,然后通过 javascript 排除结果。但我想有更好的方法吗?

谢谢!

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    你可以试试这个...但我不确定它是否适用于 10000 个文档

    db.collection.aggregate([
      {
        $group: {
          _id: null,
          names: {
            $push: "$name"
          }
        }
      },
      {
        $project: {
          newArray: {
            $setDifference: [
              [
                "name1",
                "name2",
                "name3",
                "name4"
              ],
              "$names"
            ]
          }
        }
      }
    ])
    

    这里是code snippet

    【讨论】:

      【解决方案2】:

      您可以使用mongodb的$nin运算符从集合中找出不属于用户指定的元素数组的所有名称:

      var newArray = []    
      
       db.collection.find({
          name: {
              $nin: myArray
          }
      }).forEach(function(doc) {
          newArray.push(doc.name)
      })
      

      【讨论】:

      • 不,OP 想要的是过滤 myArray,而不是过滤集合
      • 更新后的答案将返回尚未作为名称存在的名称数组。
      • 是的,基于问题中的这一行:'并且他想找出哪些名称不在数据库中,所以我需要返回一个包含所有未找到名称的新数组在我的收藏中'
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-17
      • 1970-01-01
      • 1970-01-01
      • 2014-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多