如何限制MongoDB中显示的嵌套文档的数量

如何限制MongoDB中显示的嵌套文档的数量,mongodb,nested,document,Mongodb,Nested,Document,我有一个父文档数组,由20到500个嵌套文档组成。如何限制为每个父文档显示的嵌套文档的数量 [{ id title users: [{ user_id: 1, timestamp: 2354218, field3: 4 }, { user_id: 1, timesta

我有一个父文档数组,由20到500个嵌套文档组成。如何限制为每个父文档显示的嵌套文档的数量

[{
        id
        title
        users: [{
                user_id: 1,
                timestamp: 2354218,
                field3: 4
            }, {
                user_id: 1,
                timestamp: 2354218,
                field3: 4
            }, {
                user_id: 1,
                timestamp: 2354218,
                field3: 4
            },
            ...
        ]

    }, {

    },
    ...
]
db.collection.aggregate([{ $project: { title: 1, nUsers: { $slice: [ "$users", n ] } } ])
下面是我的文档和嵌套文档的结构

[{
        id
        title
        users: [{
                user_id: 1,
                timestamp: 2354218,
                field3: 4
            }, {
                user_id: 1,
                timestamp: 2354218,
                field3: 4
            }, {
                user_id: 1,
                timestamp: 2354218,
                field3: 4
            },
            ...
        ]

    }, {

    },
    ...
]
db.collection.aggregate([{ $project: { title: 1, nUsers: { $slice: [ "$users", n ] } } ])
我想限制每个父文档显示的用户数。如何操作?

我的问题
您可以尝试下面的查询。使用
$slice
在每个文档的嵌套文档数组中最多获取第一个
n
元素

[{
        id
        title
        users: [{
                user_id: 1,
                timestamp: 2354218,
                field3: 4
            }, {
                user_id: 1,
                timestamp: 2354218,
                field3: 4
            }, {
                user_id: 1,
                timestamp: 2354218,
                field3: 4
            },
            ...
        ]

    }, {

    },
    ...
]
db.collection.aggregate([{ $project: { title: 1, nUsers: { $slice: [ "$users", n ] } } ])
或者使用常规查询

db.collection.find({}, { title: 1, nUsers: {$slice: n } })

正如您所提到的,我已经展示了使用$slice的查询。我希望你已经明白了。我怎样才能限制我在“用户”中显示的字段的数量呢。就像我有用户的邮政编码,职业,性别,年龄,。。。我只想显示邮政编码和职业。看看这是否有帮助