【问题标题】:MongoDB: how do I check that all array entries are unique in the entire collection?MongoDB:如何检查所有数组条目在整个集合中是否唯一?
【发布时间】:2017-07-30 21:06:31
【问题描述】:

mongo 用户的小脑筋急转弯。

我有一个文档集合,例如

{
    "_id" : ObjectId("19628f4f0545a733185b672f"),
    "name" : "hello",
    "items" : [ 
        {
            "itemNumber" : 12512,
            "value" : "let"
        }, 
        {
            "itemNumber" : 2546,
            "value" : "put"
        }
    ]
}

我需要确保每个项目的 itemNumber 在集合中全局唯一。

在 SQL 数据库中,我将有一个单独的项目表,用于检查数字是否唯一的查询类似于

select count(1) 
from (
   select itemNumber, count(itemNumber) as cnt 
   from items 
   group by itemNumber) sel 
where cnt>1;

生成的0 意味着所有itemNumbers 都是唯一的。 (可能有更好的方法在 SQL 中进行检查)

对于 MongoDB,我能想到的唯一解决方案是

a) 使用forEach 将所有项目提取到单独的集合中

b) 做一个简单的聚合

db.items.aggregate(
    { $group : { _id : '$itemNumber', count : {$sum : 1} } },
    { $out : "cnt" }
)

c)db.cnt.find({count: {$gt: 1}}).count()

有没有单查询的方法呢?

性能说明:集合大约 3M 文档,每个 2,2KB。我注意到包含 $group 的聚合在此集合上会一直运行。

【问题讨论】:

标签: mongodb aggregation-framework


【解决方案1】:

这样的事情怎么样:

db.items.aggregate(
    { $unwind: "$items" }    ,
    { $group : { _id : '$items.itemNumber', count : { $sum : 1 } } },
    { $match: { "count": { $gt: 1 } } }
)

【讨论】:

    猜你喜欢
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 2012-12-12
    • 2014-04-19
    • 2011-07-19
    • 1970-01-01
    相关资源
    最近更新 更多