简体   繁体   中英

MongoDB aggregation by array field

Suppose my collection contains documents like:

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

{"email": "john@abc.com", "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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM