j3d
j3d

Reputation: 9734

MongoDB: How to concatenate document ids to a unique string

Given a collections like this...

{ "_id" : ObjectId("5546371e470000570184a633"), "name" : "John", "age": 31 }
{ "_id" : ObjectId("5546381e470000570184a634"), "name" : "Mike", "age": 35 }
{ "_id" : ObjectId("5546391e470000570184a635"), "name" : "Jack", "age": 28 }

... how do I merge the _id of all the guys older than 30? The result I'm looking for is

{ "_ids" : "5546371e470000570184a633,5546381e470000570184a634,5546391e470000570184a635" }

I could used find and then iterate over the result to concatenate the _ids... but perhaps the is a more convenient way.

Upvotes: 0

Views: 433

Answers (1)

Salvador Dali
Salvador Dali

Reputation: 222761

I do not see any problem with your approach. Here is a slightly different one:

db.coll.distinct("_id", {age: {$gt: 30}}).map(function(el){
  return el.str;
}).join(",")

I do realize that all the _id are distinct by definition.

Upvotes: 3

Related Questions