[英]MongoDB Aggregation - Query array of objects
I have a collection with this data:我有一个包含这些数据的集合:
[
{
_id: "123",
number: 10,
users: [
{
amount: 20
}
]
},
{
_id: "456",
number: 20,
users: [
{
amount: 10
}
]
}
]
I need to find documents where users[0].amount
is greater than or equal to number
.我需要找到
users[0].amount
大于或等于number
的文档。 I have the following Mongoose query:我有以下 Mongoose 查询:
Model.aggregate([
{
$match: {
$expr: {
$and: [
{ $gte: ["$users.0.amount", "$number"] },
...
]
}
}
}
]);
However, this doesn't seem to be filtering the documents properly.但是,这似乎没有正确过滤文档。 I'm assuming
$users.0.amount
isn't the correct syntax.我假设
$users.0.amount
不是正确的语法。 How can I fix this?我怎样才能解决这个问题?
$expr requires Aggregation Framework's syntax so you have to use $arrayElemAt instead: $expr需要聚合框架的语法,所以你必须使用$arrayElemAt代替:
{ $gte: [ { $arrayElemAt: [ "$users.amount", 0] }, "$number" ] }
where users.amount
is an array of numbers其中
users.amount
是一个数字数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.