2017-02-15 37 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和職業。 –