【问题标题】:How to limit the number of nested documents shown in MongoDB [duplicate]如何限制 MongoDB 中显示的嵌套文档的数量 [重复]
【发布时间】:2017-07-04 15:24:25
【问题描述】:

我有一组由 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 ] }
    }}
]);

【问题讨论】:

    标签: mongodb nested document


    【解决方案1】:

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

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

    或使用常规查询。

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

    【讨论】:

    • 我已经展示了我在 $slice 中使用的查询,正如您所提到的。但我似乎没有让它工作
    • 我希望你已经明白了。
    • 如何限制我在“用户”中显示的字段数量。就像我有用户 zip_code、职业、性别、年龄……我只想显示 zip_code 和职业。
    猜你喜欢
    • 1970-01-01
    • 2018-11-24
    • 2012-01-17
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 2019-04-20
    • 2022-10-17
    相关资源
    最近更新 更多