【发布时间】: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