1

I have a record of following format...

{
"_id" : ObjectId("609cd99d1af4ac1036d78f7d"),
"userrole" : "admins",
"locks" : [
{
"userid" : "2932fb99-4c41-4342-99e0-af15f8146da0",
"useremail" : "fsasdev@gmail.com",
"filepath" : "output/notes.txt",
.
.
}
]
}

How to fetch userid,useremail where filepath matches"output/notes.txt"?

Tushar Gupta - curioustushar
  • 54,013
  • 22
  • 95
  • 103
s d
  • 27
  • 6

1 Answers1

1

Demo - https://mongoplayground.net/p/FFYYCqOmPx-

Use $

The positional $ operator limits the contents of a to return the first element that matches the query condition on the array.

db.collection.find({
  "locks.filepath": "output/notes.txt" // query 
},
{
  "locks.$": 1 // projection
})

Demo - https://mongoplayground.net/p/TLqmuhN6H3q

db.collection.aggregate([
  {
    $match: { "locks.filepath": "output/notes.txt" } // filter to reduce load in unwind
  },
  { $unwind: "$locks" }, //  break into individual documents
  {
    $match: { "locks.filepath": "output/notes.txt" } // filter
  },
  {
    $replaceRoot: { "newRoot": "$locks" } // set root as $locks
  }
])
Tushar Gupta - curioustushar
  • 54,013
  • 22
  • 95
  • 103