聚合数组中的对象匹配多个条件的文档 [英] Aggregate documents where objects in array matches multiple conditions
问题描述
我有一个包含类似这样的文档的集合:
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屋!