2017-02-15 39 views
1

我有由20-500个嵌套文档组成的父文档数组。我怎样限制为每个父文档显示的嵌套文档的数量。如何限制在MongoDB中显示的嵌套文档的数量

下面是我的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 ] } 
    }} 
]); 

回答

2

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

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

或使用常规查询。

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

我已经显示了我正在使用$ slice的查询,正如您所提到的。但我似乎没有得到它的工作 –

+0

我希望你已经明白了这一点。 – Veeram

+0

如何限制我在“用户”中显示的字段数量。就像我有用户zip_code,职业,性别,年龄,...我只想显示zip_code和职业。 –