0

I'm using version 3.2.3. How do I get the function to return just a subdocument where cfmstatus == 'down' rather than the whole document?

db.test1.insert({
  _id: "host1",
  "interfaces" : [
    {
      "inf": "ge-10/3/5",
      "cfmstatus": "up"
    },
    {
      "inf": "ge-7/1/2",
      "cfmstatus": "down"
    }
  ]
});

db.test1.find({
  $where: function () {
      for (var index in this.interfaces)
          if (this.interfaces[index].cfmstatus == 'down')
              return this;
  }
});

Thanks in advance.

Curious Mau
  • 1
  • 1
  • 1
  • Try with `$elemMatch` projection `db.test1.find({}, { interfaces: { $elemMatch: { cfmstatus: "down" } } })` – Ashh Jul 17 '18 at 03:30
  • Possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – Ashh Jul 17 '18 at 03:33
  • That worked. Thanks. – Curious Mau Jul 17 '18 at 03:57

2 Answers2

0

According to description as mentioned into above question,as a solution to it please try executing following mongodb query

db.getCollection("test1").find({
    interfaces: {
        $elemMatch: {
            cfmstatus: 'down'
        }
    }
}, {
    'interfaces.$': 1
})

Into above query $elemMatch operator is used to filter a value into an array element and positional operator $ will return first matching sub document belonging to an embedded document.

Rubin Porwal
  • 3,736
  • 1
  • 23
  • 26
0

Use $elemMatch

db.test1.find( { interfaces: { $elemMatch: {  cfmstatus: down } } } )

https://docs.mongodb.com/v3.2/reference/operator/query/elemMatch "$elemMatch documentation"

Abhi Anand
  • 21
  • 1
  • 7