0

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.

0

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot, it actually worked. I will read more about aggregation.
Can you please tell how I can write query based on myFormat and then get only the documents inside rows which has that myFormat? I have edited the question also. Thanks for the help.
@user9275416 : ok basic thing in SO, Once a question is solved, Please accept it to close it, do not edit it to make it complex. If there are minor changes then it should be ok, but please don't put in entire new requirement into the same question that's makes everything look complicated, Raise a new question if there is no other question that matches your req !! Please give me sometime on this new one..
Okay Understood

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.