如何限制MongoDB中显示的嵌套文档的数量[重复](How to limit the number of nested documents shown in MongoDB [duplicate])

编程入门 行业动态 更新时间:2024-10-04 19:32:06
如何限制MongoDB中显示的嵌套文档的数量[重复](How to limit the number of nested documents shown in MongoDB [duplicate])

这个问题在这里已有答案:

如何在mongo集合中获取子文档数组的分页/切片数据? 2个答案

我有一系列父文档,包括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.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 ] } }} ]);

This question already has an answer here:

How to get paginated/sliced data of subdocument array in mongo collection? 2 answers

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

最满意答案

您可以尝试以下查询。 使用$slice可以获取每个文档的嵌套文档数组中的前n元素。

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

或使用常规查询。

db.collection.find({}, { title: 1, nUsers: {$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 ] } } ])

or Using regular query.

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

更多推荐

本文发布于:2023-08-07 13:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464102.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   数量   文档   limit   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!