user9275416
user9275416

Reputation: 35

MongoDB multiple levels embedded array query

I have a document like this:

{
 _id: 1,
 data: [
        {
           _id: 2,
           rows: [
                  {
                   myFormat: [1,2,3,4]
                  },
                  {
                   myFormat: [1,1,1,1]
                  }
                 ]
        },
        {
           _id: 3,
           rows: [
                  {
                   myFormat: [1,2,7,8]
                  },
                  {
                   myFormat: [1,1,1,1]
                  }
                 ]
        }
       ]
},

I want to get distinct myFormat values as a complete array.

For example: I need the result as: [1,2,3,4], [1,1,1,1], [1,2,7,8]

How can I write mongoDB query for this?

Thanks for the help.

Upvotes: 0

Views: 77

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

Please try this, if every object in rows has only one field myFormat :

db.getCollection('yourCollection').distinct('data.rows')

Ref : mongoDB Distinct Values for a field

Or if you need it in an array & also objects in rows have multiple other fields, try this :

db.yourCollection.aggregate([{$project :{'data.rows.myFormat':1}},{ $unwind: '$data' }, { $unwind: '$data.rows' },
{ $group: { _id: '$data.rows.myFormat' } },
{ $group: { _id: '', distinctValues: { $push: '$_id' } } },
{ $project: { distinctValues: 1, _id: 0 } }])

Or else:

db.yourCollection.aggregate([{ $project: { values: '$data.rows.myFormat' } }, { $unwind: '$values' }, { $unwind: '$values' },
{ $group: { _id: '', distinctValues: { $addToSet: '$values' } } }, { $project: { distinctValues: 1, _id: 0 } }])

Above aggregation queries would get what you wanted, but those can be tedious on large datasets, try to run those and check if there is any slowness, if you're using for one-time then if needed you can consider using {allowDiskUse: true} & irrespective of one-time or not you need to check on whether to use preserveNullAndEmptyArrays:true or not.

Ref : allowDiskUse , $unwind preserveNullAndEmptyArrays

Upvotes: 2

Related Questions