0

Created a collection for the array “test”

({a:"foo", b:[10,20,30]}) 
({a:"foo", b:[15,25,35]}) 
({a:"foo", b:[10,40,50]}) 
({a:"bar", b:[10,60,70]}) 

MongoDB query to find all documents which has the a distinct values and b value as “10”.

I have tried this

db.test.find({b: {$elemMatch : {$in : [10] }}})

{ "_id" : ObjectId("5bda7ea8aabd746c974b5faa"), "a" : "foo", "b" : [ 10, 20, 30 ] }
{ "_id" : ObjectId("5bda7f74aabd746c974b5fac"), "a" : "foo", "b" : [ 10, 40, 50 ] }
{ "_id" : ObjectId("5bda7f74aabd746c974b5fad"), "a" : "bar", "b" : [ 10, 60, 70 ] }

this is giving output of second one, how to get distinct value of a?

2 Answers 2

1

I got my answer.

db.test.distinct( "a" , {b: {$elemMatch : {$in : [10] }}})

Output:

[ "foo", "bar" ]
Sign up to request clarification or add additional context in comments.

Comments

0
db.collection.aggregate([{
    $unwind: "$b"
  },
  {
    $group: {
      _id: "$b",
      a_vals: {
        $addToSet: "$a"
      },
      count: {
        $sum: 1
      }
    }
  },
  {
    $match: {
      count: {
        $gt: 1
      }
    }
  }
]);

Playground link: https://mongoplayground.net/p/qR2mTqXPs3o

Comments

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.