Search code examples
databasemongodbmongoosenosql

how to get object from array by value inside desired object by mongoose


i have following bson data in mongoDB

{
 [
  {
     partyName : "p1",
     poNumber : "789",
  },
  {
     partyName : "p2",
     poNumber : "700",
  },
  {
     partyName : "p3",
     poNumber : "889",
  }
 ]
}

i want object from partyName for example if partyName is p1 then i want this

{
     partyName : "p1",
     poNumber : "789",
  }

i searched on the internet but not find relative result, all i found that query.elemMatch may help but i don't know how to use it please help me with the solution ( i want to use only mongoose )


Solution

  • You can try this. Fill in the EntityName and mainEntityName parts as your schema's names:

    await EntityName.findOne({ mainEntityName: { $elemMatch: { partyName: "p1" } } });
    

    Instead of p1, add your parameter that came from the req.query.

    To reach all elements that match with your filter; use the find() method:

    await EntityName.find({ mainEntityName: { $elemMatch: { partyName: "p1" } } });