【问题标题】:Finding which elements in an array do not exist for a field value in MongoDB查找数组中的哪些元素对于 MongoDB 中的字段值不存在
【发布时间】:2014-06-25 08:58:16
【问题描述】:

我有一个集合用户如下:

{ "_id" : ObjectId("51780f796ec4051a536015cf"), "userId" : "John" }
{ "_id" : ObjectId("51780f796ec4051a536015d0"), "userId" : "Sam" }
{ "_id" : ObjectId("51780f796ec4051a536015d1"), "userId" : "John1" }
{ "_id" : ObjectId("51780f796ec4051a536015d2"), "userId" : "john2" } 

现在我正在尝试编写一个代码,如果用户提供的 id 已经存在于 DB 中,它可以向用户提供 userId 的建议。在同一例程中,我只是将值从 1 到 5 附加到例如,如果用户选择 userId 为 John,则需要在数据库中检查 Id 的建议用户名数组将如下所示

[John,John1,John2,John3,John4,John5].

现在我只想对 Db 执行它并找出 DB 中不存在哪些建议值。因此,我不想选择任何文档,而是想在建议的数组中选择用户集合中不存在的值。

高度赞赏任何指针。

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您的一般方法是您希望找到集合中已经存在的“userId”的“不同”值。然后,您将这些与您的输入选择进行比较以查看差异。

    var test = ["John","John1","John2","John3","John4","John5"];
    
    var res = db.collection.aggregate([
        { "$match": { "userId": { "$in": test } }},
        { "$group": { "_id": "$userId" }}
    ]).toArray();
    
    res.map(function(x){ return x._id });
    
    test.filter(function(x){ return res.indexOf(x) == -1 })
    

    最终结果是用户 ID 在您的初始输入中不匹配:

    [ "John2", "John3", "John4", "John5" ]
    

    这里的主要操作符是$in,它将一个数组作为参数并将这些值与指定的字段进行比较。 .aggregate() 方法是最好的方法,.distinct() 方法中有一个简写的 mapReduce 包装器,它直接只生成数组中的值,删除对像 .map() 这样的函数的调用以去除给定的值关键:

    var res = db.collection.distinct("userId",{ "userId": { "$in": test } })
    

    但它的运行速度应该会明显变慢,尤其是在大型集合上。

    另外,不要忘记为您的“userId”编制索引,并且您可能希望它是“唯一的”,所以您真的只想要 $match.find() 结果:

    var res = db.collection.find({ "$in": test }).toArray()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-30
      • 2023-02-03
      • 2016-05-28
      • 2019-11-21
      相关资源
      最近更新 更多