获取一个mongodb对象数组

时间:2016-08-16 12:55:16

标签: mongodb subdocument

我的集合中有很多子文档,我只想获取对象的配置数组(非空)并忽略所有其他对象

我在stackoverflow Find MongoDB records where array field is not empty (using Mongoose)

上尝试了其中一个解决方案

它返回配置数组,但也返回我的集合中的其他对象

这是示例数据

http://imgur.com/a/RXLGv

这个查询返回了我所有的对象配置数组,但它也返回了我不想要的空数组,对此有什么解决方法吗?

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

示例数据

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,

          }
        }]

我想忽略空数组,只想获取配置对象

1 个答案:

答案 0 :(得分: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}});