addToSet using java api

15 views
Skip to first unread message

Omprakash Verma

unread,
Jun 25, 2014, 9:01:28 AM6/25/14
to mongod...@googlegroups.com
Dear All,
                We are now using mongodb for our internal project to get experience on it. Here is one issue, in which I need your help..


I have a table ..

book_issued
Fields : user_id, book_id

Table data are like 
user_id  book_id
1           1
1           4
2           5
2           6


I want to show it as grouped using java api.

user_id  book_id
1           1,4
2           5,6

Please suggest and help me. We are using $match and $group.


Thanks,
Op

Rob Moore

unread,
Jun 25, 2014, 2:56:40 PM6/25/14
to mongod...@googlegroups.com

I just pushed an example application using the asynchronous Java driver up to GitHub.

The pipeline it generated is:

'$pipeline' : [
  {
    '$match' : {
      'user_id' : {
        '$gt' : 0,
        '$lt' : 10
      },
      'book_id' : {
        '$gt' : 0,
        '$lt' : 10
      }
    }
  }, 
  {
    '$group' : {
      '_id' : '$user_id',
      'book_id' : { '$addToSet' : '$book_id' }
    }
  }
]

And gives the results:

{
  '_id' : 2,
  'book_id' : [
    6, 
    5
  ]
}
{
  '_id' : 1,
  'book_id' : [
    4, 
    1
  ]
}
Reply all
Reply to author
Forward
0 new messages