0

I am trying to write a query in mongoDB with an OR operation inside a list of objects and the query should return one field of that document rather than returning the complete document. Let say I have database like this

{
"PID : "PID-1",
PriceList : {
  {
    cityId:1,
    stateId:2,
    country:X,
  },
  {
    cityId:1,
    stateId:3,
    country:X,
  },
  {
    cityId:2,
    stateId:2,
    country:X,
  }
 }
},
{
"PID : "PID-2",
PriceList : {
  {
    cityId:1,
    stateId:2,
    country:X,
  }
 }
}

Now, If I give my input as PID = PID-1, CityId = 1, country = X. Then I should get this o/p

{
PriceList : {
{
    cityId:1,
    stateId:2,
    country:X,
  },
  {
    cityId:1,
    stateId:3,
    country:X,
  }
 }
}

Let's say if I give input as PID = PID-1 and country = X then o/p should be

{
  {
    cityId:1,
    stateId:2,
    country:X,
  },
  {
    cityId:1,
    stateId:3,
    country:X,
  },
  {
    cityId:2,
    stateId:2,
    country:X,
  }
}

I tried various queries but could not solve it.

Meg
  • 88
  • 1
  • 8
  • You can test out your queries using https://npm.runkit.com/mingo. – kofrasa Jan 08 '22 at 22:18
  • What you want is the $elemMatch operator – kofrasa Jan 08 '22 at 22:25
  • Hi @kofrasa, I want to use mogoDB with springboot. Not sure about nodejs. – Meg Jan 09 '22 at 04:21
  • 1
    See answer to https://stackoverflow.com/questions/29026662/mongodb-elemmatch-multiple-elements-in-array – kofrasa Jan 10 '22 at 04:36
  • Hi @kofrasa, this helped alot. Can you please help here also ? https://stackoverflow.com/questions/70665046/mapped-result-is-different-from-raw-result-in-mongodb-aggregation – Meg Jan 11 '22 at 10:17

0 Answers0