2

Kindly help me in the following scenario. Following is sample data single document. Among all document, I need single document, with array values as expected (status active, status other than active etc).

{
"_id":.......
"type":"dept",
"values":[
  {
    "name":"dept 1",
    "status":"active"
  },
  {
    "name":"dept 2",
    "status":"active"
  },
  {
    "name":"dept 3",
    "status":"deleted"
  },
  {
    "name":"dept 4",
    "status":"active"
  },
  {
    "name":"dept 5",
    "status":"active"
  },
  {
    "name":"dept 6",
    "status":"disabled"
  },
 ]
}

Expected Result

1) Get all Active (inside the array)

{
"_id":.......
"type":"dept",
"values":[
  {
    "name":"dept 1",
    "status":"active"
  },
  {
    "name":"dept 2",
    "status":"active"
  }
  {
    "name":"dept 4",
    "status":"active"
  },
  {
    "name":"dept 5",
    "status":"active"
  }
 ]
}

2) Get other than active (inside the array)

 {
  "_id":.......
  "type":"dept",
  "values":[

   {
     "name":"dept 3",
     "status":"deleted"
   },
   {
     "name":"dept 6",
     "status":"disabled"
    },
  ]
 }

Kindly help me querying in getting above expected result. I wand to retrive the document with the array value as expected in above example.

solomon abel
  • 166
  • 2
  • 7

1 Answers1

1

you question has an answer here: How to search in array of object in mongodb

but in short you can do this:

db.collection.find({values: {$elemMatch: {status: 'active'}}})

hope it helps you

ganjim
  • 1,234
  • 1
  • 16
  • 30