【问题标题】:MongoDB - find item in list and return distinct documentsMongoDB - 在列表中查找项目并返回不同的文档
【发布时间】:2015-03-28 16:23:36
【问题描述】:

假设我在 MongoDB 中有一组文档。是否存在用于查看字符串是否在值列表中的查询,如果是,则仅返回基于特定键值的不同文档?

{
    "_id" : ObjectId("5504d11b6946aa2b4dff7e99"),
    "states" : [ 
        "AL", 
        "AZ", 
        "TX"
    ],
    "name" : "Foo",
    "rating" : "NR",
    "url" : "www.domain.com",
};

   {
        "_id" : ObjectId("5504d11b6946aa2b4dff7e98"),
        "states" : [ 
            "AL", 
            "NJ", 
            "NY"
        ],
        "name" : "Bar",
        "rating" : "NR",
        "url" : "www.domain.com",
    };

  {
        "_id" : ObjectId("5504d11b6946aa2b4dff7e97"),
        "states" : [ 
            "AL", 
            "AZ", 
            "TX"
        ],
        "name" : "The Grinch",
        "rating" : "NR",
        "url" : "www.domain.net",
    }

例如, 如果 ALstates 中,则仅返回 URL 不同的集合 - 将返回上述示例中的第一个和最后一个集合。

db.collections.find({"states":{'$in':["AL"]}})

是我用来在列表中查找状态的。

db.collections.aggregate({ $group: { _id: '$url', n: { $max: '$states' } } }).

result 是我用来根据域获取不同集合的方法。

我遇到麻烦的地方是将两者结合在一个语句中。

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    看起来像这样:

    db.collection.aggregate([
        {$match: {$states: 'AL'}},
        {$group:{_id: '$url'}}
    ]);
    

    $max$in 是您通话中不必要的费用。

    【讨论】:

    • 未捕获的异常:聚合失败:{“errmsg”:“异常:错误查询:BadValue 未知顶级运算符:$states”,“code”:16810,“ok”:0 }
    • 这可行,但是结果中缺少其他键:值对:db.carriers.aggregate([ {$match: {"states":{'$in':["AL"]}}}, {$group:{_id: '$url'}} ]).result
    猜你喜欢
    • 2015-03-26
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多