汇总文档,其中数组中的对象匹配多个条件 [英] Aggregate documents where objects in array matches multiple conditions

查看:78
本文介绍了汇总文档,其中数组中的对象匹配多个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似这样的文件的收藏集:

I have a collection with documents similar to such:

{
    "_id": ObjectId("xxxxx"),
    "item": [
        { "property": ["attr1", "+1"] },
        { "property": ["attr2", "-1"] }
    ]
}

{
    "_id": ObjectId("xxxxy"),
    "item": [
        { "property": ["attr1", "-1"] },
        { "property": ["attr2", "0"] }
    ]
}

{
    "_id": ObjectId("xxxxz"),
    "item": [
        { "property": ["attr1", "0"] },
        { "property": ["attr2", "+1"] }
    ]
}

最好使用聚合管道,并且仅当任一属性符合一个以上条件时,才可以使用任何方法来匹配文档?

Preferably using an aggregation pipeline, is there any way to match the document if and only if any one of the properties match more than one condition?

例如,我想要一个查询,其中数组中的一个对象同时符合以下两个条件:

For example, I want a query where one object in the array matches both of these conditions:

("item.property": "attr1") AND ("item.property": /^\+/)

也就是说,它是一个单个属性,其中包含"attr1"和一个以"+"开头的元素.

That is, a single property where it contains "attr1" and an element that starts with "+".

但是,使用我当前的查询如下:

However, using my current query that looks like this:

collection.aggregate(
    { $match:
        { $and: 
            [
                { "item.property": "attr1" },
                { "item.property": /^\+/ }
            ]
        }
    }

这将匹配第一个文档和最后一个文档,因为这两个文档都包含一个带有"attr1"的属性和一个带有"+"状态的元素.但是,我不希望此查询与最后一个文档匹配,因为以"+"开头的元素不属于数组中的同一对象.

This would match both the first and last document because both contain a property with "attr1" and an element that stats with "+". However, I do not want this query to match the last document, since the element that starts with "+" does not belong to the same object in the array.

有什么方法可以使用聚合框架来实现这种行为吗?

Is there any way to achieve this behavior using the aggregation framework?

推荐答案

您可以将以下查询与 $elemMatch 来匹配数组的两个值.

You can use the below query with $elemMatch to match the array's both values.

类似

db.collection_name.aggregate({
  "$match": {
    "item": {
      "$elemMatch": {
        "property.0": "attr1",
        "property.1": /^\+/
      }
    }
  }
});

此外,您可以使用 $all 运算符您不想引用数组索引.

Also, you can use $all operator if you don't want to reference array index.

db.collection_name.aggregate({
  "$match": {
    "item": {
      "$elemMatch": {
        "property": {
          "$all": [
            "attr1",
            /^\+/
          ]
        }
      }
    }
  }
});

这篇关于汇总文档,其中数组中的对象匹配多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆