Ludwig Magnusson
Ludwig Magnusson

Reputation: 14379

Get a result of sub documents located in arrays in mongodb

Let's say that I have a database collection called users in mongodb and the documents look like this:

[{
  _id: 'userId1'
  actions: [{
    name: 'SingUp',
    data: '...',
    time: '1'
  }, {
    name: 'CreatePost',
    data: '...',
    time: '4'
  }]
}, {
  _id: 'userId2'
  actions: [{
    name: 'SingUp',
    data: '...',
    time: '2'
  }, {
    name: 'CreatePost',
    data: '...',
    time: '3'
  }, {
    name: 'CreatePost',
    data: '...',
    time: '5'
  }]
}]

What would be the most efficient way to get only the action documents that have the name CreatePost, all sorted by time? I.e. the result I want is this:

[{
  name: 'CreatePost',
  data: '...',
  time: '3'
}, {
  name: 'CreatePost',
  data: '...',
  time: '4'
}, {
  name: 'CreatePost',
  data: '...',
  time: '5'
}]

Upvotes: 0

Views: 24

Answers (1)

felix
felix

Reputation: 9285

a quick solution is to use $unwind, filter out documents with $match and finally sort using $sort like this:

db.users.aggregate([
  {$unwind: "$actions"},
  {$match: {"actions.name": "CreatePost"}},
  {$project: {"name": "$actions.name", "data": "$actions.data", "time": "$actions.time"}},  
  {$sort: {"time": 1}}
]) 

Upvotes: 1

Related Questions