user2552172
user2552172

Reputation: 1

MongoDB aggregation by array field

Suppose my collection contains documents like:

{"email": "[email protected]", "fb" : { "name" : { "full" : "Jim Bent"} }, "apps": ["com.abc.1", "com.abc.2"]}

{"email": "[email protected]", "fb" : { "name" : { "full" : "John Smith"}}, "apps": ["com.abc.1", "com.abc.3" ]}

I want to write a query and export it out via a csv file that outputs the emails, fb.name.full grouping by the "apps" array fields in this entire collection. That is: for "com.abc.1", it outputs Jim Bent with his email and John Smith and email. For "com.abc.2", it will output only Jim Bent, whilst for "com.abc.3", it will output only John Smith.

I have researched a bit, but mongoexport doesn't allow complex queries, and I am not able to write an $unwind function either. So i am hitting a wall.

Any advice is appreciated. Thank you.

Upvotes: 0

Views: 124

Answers (1)

xlembouras
xlembouras

Reputation: 8295

You can do this with Javascript and the mongo shell by creating a file (eg: myquery.js) with the following code:

printjson(
  db.collection.aggregate([
   {$unwind: '$apps'},
   {$group: { _id: '$apps', info: { '$push': { email: '$email', name: '$fb.name.full'}}}},
   {$project: {app: '$_id', info: 1, '_id': 0}}
  ]))

then you can perform the query from the command line as:

mongo database myquery.js

Upvotes: 1

Related Questions