如何限制MongoDB中显示的嵌套文档数 [英] How to limit the number of nested documents shown in MongoDB

查看:25
本文介绍了如何限制MongoDB中显示的嵌套文档数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组由嵌套文档组成的父文档数组,范围在 20 到 500 之间.如何限制为每个父文档显示的嵌套文档的数量.

I have array of parent documents consisting of nested documents ranging between 20 to 500. How can I limit the number of nested documents shown for each parent document.

下面是我的文档和嵌套文档的结构.

below is the structure of my Document and nested document.

[{
        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.movies.aggregate(
[{$match: {
    "movie_title":  "Toy Story (1995)"}
  },{
    $lookup: {
        from: "users",
        localField: "users.user_id",
        foreignField: "users.id",
        as: "users"
    }
},
{$project: {

        movie_title: "$movie_title",
        users: { $slice: [ "$users", 1 ] }
    }}
]);

推荐答案

你可以试试下面的查询.使用 $slice 获取每个文档的嵌套文档数组中至多前 n 个元素.

You can try below query. Use $slice to get at most first n elements in nested documents array for each document.

db.collection.aggregate([{ $project: { title: 1, nUsers: { $slice: [ "$users", n ] } } ])

或使用常规查询.

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

这篇关于如何限制MongoDB中显示的嵌套文档数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆