0

I have many sub documents in my collection, I only want to fetch Configuration array of objects (not empty) and ignore all others object

I tried one of the solution on stackoverflow Find MongoDB records where array field is not empty (using Mongoose)

it returns me the configuration array but also other objects of my collection

here is the sample data

https://i.stack.imgur.com/Y0vSN.jpg

this query returns me all the configuration array of objects but it also returns me empty arrays which I do not want, any solution for this ?

return Company.find({}, {
  "configuration": 1
}, {
  "configuration": {
    "$not": {
      "$size": 0
    }
  }
})

sample data

configuration: [],
configuration: [],
configurtaion: [{
          "id": "2013",
          "name": "TRUEAUTO",
          "locationId": null,
          "deviceIdentifier": "850",
          "serialNumber": "",
          "modelNumber": "OptiPlex 3010",
          "tagNumber": null,
          "purchaseDate": null,
          "installationDate": "2016-07-28T00:00:00.000Z",
          "warrantyExpirationDate": null,
          "vendorNotes": null,
          "notes": null,
          "lastLoginName": null,
          "billFlag": "false",
          "backupServerName": null,
          "backupProtectedDeviceList": null,

          }
        }]

I want to ignore empty arrays and only to get configuration objects only

Community
  • 1
  • 1

1 Answers1

0
//You can use $exist property with $size 

Company.find({ configuration: { $exists: true, $not: {$size: 0} } }, {
  "configuration": 1
})
//Or you can check
Company.find({'configuration.0': {$exists: true}});
Shantanu Madane
  • 617
  • 5
  • 14