【问题标题】:Search MongoDB Array of Objects where property has same value for more than 1 array element搜索 MongoDB 对象数组,其中属性具有超过 1 个数组元素的相同值
【发布时间】:2015-05-17 02:11:55
【问题描述】:

我有一个 Mongo 产品集合,其中包含一个对象数组的类别字段。

{
    "_id" : ObjectId("XXX"),
    "title" : "Cool Product",
    "details" : "Some Details",
    "categories" : [ 
        {
            "name" : "Cat1",
            "isPrimary" : true
        }, 
        {
            "isPrimary" : true,
            "name" : "Cat2"
        }, 
        {
            "name" : "Cat3"
        }
    ]
}

因为一个产品可以有多个类别,我想强制一个主要类别关系(一对一)。但是,在数据迁移中,某些文档对于文档中的多个类别具有 isPrimary 属性 true。我需要为类别数组中的多个数组元素找到 isPrimary 为真的产品。这是我目前所拥有的:

db.products.find({ "categories" : { "$elemMatch" : { "isPrimary" : { "$exists" : false}}}})

但这只会给我一个数组元素不存在 isPrimary 的结果。我不知道如何查询 isPrimary 在多个数组元素上具有相同的值。此外,这也将是一个 Spring 查询:

Query query = new Query();
query.addCriteria(new Criteria().orOperator(
            Criteria.where("categories").elemMatch(Criteria.where("isPrimary").exists(false)),
            Criteria.where("categories").size(0),
            Criteria.where("categories")
            ));
query.with(new Sort(Sort.Direction.ASC, "title"));
return operations.find(query, Product.class);

【问题讨论】:

    标签: arrays mongodb spring-data mongodb-query spring-mongo


    【解决方案1】:

    你需要在这里使用聚合管道:

    db.products.aggregate([
     {$unwind:"$categories"},
     {$match:{"categories.isPrimary":true}},
     {$group:{_id:"$_id", numPrimaries:{$sum:1}}},
     {$match:{numPrimaries:{$gt:1}}}
    ])
    

    这将“展开”类别数组,仅保留具有 isPrimary 为 true 的类别,“展开”或通过原始 _id 将它们归为一组,并对有多少 isPrimary 值为 true 进行汇总,然后过滤掉只有一个的文档。您将得到具有多个类别且 isPrimary 为 true 的文档的 _id 值。

    【讨论】:

      猜你喜欢
      • 2019-10-03
      • 2017-06-02
      • 2019-08-18
      • 2020-10-25
      • 1970-01-01
      • 2022-07-03
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      相关资源
      最近更新 更多