简体   繁体   English

MongoDB 聚合 - 查询对象数组

[英]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是一个数字数组

MongoDB Playground MongoDB游乐场

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

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