terpak
terpak

Reputation: 1151

MongoDB: How to query all subdocuments of a collection

I have the collection users, and each of the user objects have a field called purchases which is an array of objects. The user object looks as follows:

User:
{
    ...
    purchases: [
        { time: 2355645366, amount: 2000 },
        { time: 2456456334, amount: 2000 },
        { time: 2435645433, amount: 2000 },
    ]
}

How do I query for all purchases among all users, as well as sort by fields such as time? The result I would expect would be an array of purchase objects.

Upvotes: 1

Views: 697

Answers (1)

Black0ut
Black0ut

Reputation: 1737

You can use aggregations operations, a very handy tool for scenarios like this

db.users.aggregate({$unwind: '$purchases'},{$sort: {'purchases.time': 1}},{$group: {_id: 0, 'purchases': {$push: '$purchases'}}})

the returned document will have the following structure :

{ "_id" : 0, "purchases" : [...all users purchases sorted by time here...]}

Upvotes: 2

Related Questions