繁体   English   中英

搜索MongoDB对象数组,其中属性对于多个数组元素具有相同的值

[英]Search MongoDB Array of Objects where property has same value for more than 1 array element

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

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

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

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);

您需要在此处使用聚合管道:

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

这将“展开”类别数组,仅保留具有isPrimary为true的类别,“保留”或通过原始_id将它们分组回来,求和多少isPrimary值为true的原始_id,然后过滤出只有一个的文档。 您将获得具有isPrimary true多个类别的文档的_id值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM