[英]MongoDb - Aggregation: How to $filter array documents with $elemMatch on a subdocument array?
I'm trying use $filter on an aggregation. 我正在尝试在聚合上使用$ filter。 I need to filter an array called 'extras' that intersect at least one of his 'seasons' with the giving 'dates'.
我需要过滤一个称为“ extras”的数组,该数组与他的至少一个“季节”与给出的“ date”相交。
Here an example: 这里是一个例子:
var from = new Date(2016, 0, 1);
var to = new Date(2016, 0, 5)
var projection = {
name: 1,
units: 1,
capacity: 1,
availabilitySeasons: { // This works
$filter: {
input: '$availabilitySeasons',
as: 'avSeason',
cond: {
$and: [{
$lte: ['$$avSeason.from', to]
}, {
$gte: ['$$avSeason.to', from]
}]
}
}
},
rate: 1,
features: 1,
extras: {
$filter: { // $elemMatch is no valid
input: '$extras',
as: 'extra',
cond: {
$elemMatch: ['$$extra.seasons', {
from: {
$lte: from
},
to: {
$gte: to
}
}]
}
}
}
};
It's possible to use $filter in this case? 在这种情况下可以使用$ filter吗? Do I have to rush through a $unwind/$group hell?
我是否必须急于完成$ unwind / $ group地狱?
Yes, you can do it. 是的,您可以做到。 As for the following example, use a condition with $lte and $gte inside a $and condition.
对于以下示例,请在$ and条件中使用带有$ lte和$ gte的条件。
$project: {
items: {
$filter: {
input: "$items",
as: "item",
cond: {
$and: [
$lt: [ "$$item.price", 100 ],
$gt: [ "$$item.price", 50 ]
] }
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.