elad BA
elad BA

Reputation: 1978

mongoDB Find by id and return subdocument matched

I have this Collection:

    {
     _id:0,
     user_id: 12,
     list: [{_.id:0, name:"john"},{_.id:1, name:"hanna"}]
    },
    {
     _id:1,
     user_id: 22,
     list: [{_.id:0, name:"john"},{_.id:1, name:"hanna"}]
    }

I want to query the collection like this: find the document by user_id and return only {_.id:0, name:"john"} inside list couldnt find any clue how to do that

some example for better explanation this what I want to achive:

const johnDoc = findOne({user_id:0}).list.findOne({name:"john"})

I know its not valid only for explaining what I want to achive.

Upvotes: 1

Views: 166

Answers (2)

Dr. Selva Mary G
Dr. Selva Mary G

Reputation: 688

You can try this $unwind

db.collection.aggregate([
  {
    $match: {
      user_id: 12,
      "list.name": "john"
    }
  },
  {
    $unwind: "$list"
  },
  {
    $match: {
      user_id: 12,
      "list.name": "john"
    }
  },
  
])

Playground

Upvotes: 1

turivishal
turivishal

Reputation: 36104

You can use the aggregation operator in find's projection from MongoDB 4.4,

  • $filter to iterate loop of list and find matching user by name property
  • $first to select the first element from filtered result
db.collection.find({
  user_id: 12
},
{
  list: {
    $first: {
      $filter: {
        input: "$list",
        cond: {
          $eq: [
            "$$this.name",
            "john"
          ]
        }
      }
    }
  }
})

Playground

Upvotes: 0

Related Questions