Home > Software design >  How to properly check if there are two model values in the object array in mongoose
How to properly check if there are two model values in the object array in mongoose

Time:11-16

I try to check if there are two keys and their values in the structure array, but I get no result, how can this be fixed?

Configuration:

[
  {
    id: 1,
    values: [
      {
        One: "One",
        Two: "Two",
        Three: "Three"
      }
    ]
  },
  {
    id: 2,
    values: [
      {
        One: "One",
        Two: "Two",
        Four: "Four"
      }
    ]
  }
]

Query

Model.find({
  "values": {
    $all: [
      {
        One: "One",
        Three: "Three",
      }
    ]
  }
})

CodePudding user response:

If I've understood correctly you can use $elemMatch to get desired value:

db.collection.find({
  "values": {
    $elemMatch: {
      One: "One",
      Three: "Three"
    }
  }
})

Example here.

Also another example with more values.

  • Related