2

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 ] }
    }}
]);
Murlidhar Fichadia
  • 2,589
  • 6
  • 43
  • 93

1 Answers1

8

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 } })
s7vr
  • 73,656
  • 11
  • 106
  • 127
  • I have shown the query I am using with $slice as you mentioned. but I dont seem to get it working – Murlidhar Fichadia Feb 15 '17 at 19:43
  • I hope you figured that out already. – s7vr Feb 15 '17 at 19:51
  • How can I limit the number of fields I am showing in "users". like I have users zip_code, occupation, gender, age,... I want to show only zip_code and occupation. – Murlidhar Fichadia Feb 15 '17 at 19:52
  • See if this helps http://stackoverflow.com/questions/42259243/mongodb-is-it-possible-to-limit-the-results-of-lookup-to-certain-fields-as-a/42259504#42259504 – s7vr Feb 15 '17 at 20:36