Dante Adams
Dante Adams

Reputation: 429

MongoDB - How to find array which only contains the specified value

Suppose I have the following documents

segments
{
  "name":"S1",
},
{
  "name":"S2",
},
{
  "name":"S3",
}

And users

users
{
  "id":1234.
  "segments":["S1","S2","S3"]
}
{
  "id":1235.
  "segments":["S1"]
}
{
  "id":1237.
  "segments":["S2"]
}
{
  "id":1236.
  "segments":["S1","S2"]
}

If i do users.find({ "segments" : "S2" }), it brings all the docs with field "S2" in it.

What I'm looking for is, array with JUST the value S2. I'm looking for this output:

{
  "id":1237.
  "segments":["S2"]
}

Because it ONLY has S2 which i'm looking for

Upvotes: 1

Views: 247

Answers (1)

Ashh
Ashh

Reputation: 46451

You can use $elemMatch projection

db.collection.find({
  segments: ["S2"]
})

Upvotes: 1

Related Questions