【问题标题】:Mongodb query nested array documents where property not nullMongodb查询嵌套数组文档,其中属性不为空
【发布时间】:2018-08-31 03:18:48
【问题描述】:

我正在尝试获取库存集合中至少一个元素的仓库字段不为空的所有文档。预期结果:仅丢弃最后的文档。

db.inventory.insertMany( [
   { item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
   { item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
   { item: "planner", instock: [ { warehouse: null, qty: 40 }, { warehouse: "B", qty: 5 } ] },
   { item: "postcard", instock: [ { warehouse: null, qty: 15 }, { warehouse: null, qty: 35 } ] }
]);

这个查询丢弃了 3 和 4。

db.getCollection('inventory').find({
    $and: [{"instock.warehouse": {$ne: null}}, {"instock.warehouse": {$exists: true}}]
})

这个返回所有元素

db.getCollection('inventory').find({
    "instock": {$elemMatch: {"warehouse": {$ne: null}, "warehouse": {$exists: true}}}
})

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    使用下面的查找查询。

    注意使用$elemMatch & $ne 比较数组的所有元素 即包括库存数组在仓库字段中没有至少一个空值的所有文档。

    db.inventory.find({"instock":{"$elemMatch":{"warehouse":{"$ne":null}}}})
    

    【讨论】:

      猜你喜欢
      • 2019-10-09
      • 2018-03-09
      • 1970-01-01
      • 2017-10-22
      • 2021-02-25
      • 2016-08-16
      • 1970-01-01
      • 2019-02-20
      相关资源
      最近更新 更多