How to limit the number of nested documents shown in MongoDB [duplicate]

邮差的信 提交于 2019-12-18 09:34:45

问题


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
            },
            ...
        ]

    }, {

    },
    ...
]

I want to limit the number of users shown for each parent document. how to?

My Query

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 ] }
    }}
]);

回答1:


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 ] } } ])

or Using regular query.

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


来源:https://stackoverflow.com/questions/42258325/how-to-limit-the-number-of-nested-documents-shown-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!