我正在尝试获取所有文档,其中instock集合中至少有一个元素的warehouse字段不为null。预期结果:仅丢弃最后一个文档。
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}}}
})