在mongoDB中提到的两个查询之间的差异

时间:2017-05-09 15:07:56

标签: mongodb bigdata

请解释下面提到的两个查询之间的区别。我正在获取第一个查询的输出但第二个没有输出。提前谢谢。

表格数据:

> db.inventory.find()
{ "_id" : ObjectId("5911ce218c302726ff998853"), "item" : "journal", "instock" : [ { "warehouse" : "A", "qty" : 5 }, { "warehouse" : "C", "qty" : 15 } ] }
{ "_id" : ObjectId("5911ce218c302726ff998854"), "item" : "notebook", "instock" : [ { "warehouse" : "C", "qty" : 5 } ] }
{ "_id" : ObjectId("5911ce218c302726ff998855"), "item" : "paper", "instock" : [ { "warehouse" : "A", "qty" : 60 }, { "warehouse" : "B", "qty" : 15 } ] }
{ "_id" : ObjectId("5911ce218c302726ff998856"), "item" : "planner", "instock" : [ { "warehouse" : "A", "qty" : 40 }, { "warehouse" : "B", "qty" : 5 } ] }
{ "_id" : ObjectId("5911ce218c302726ff998857"), "item" : "postcard", "instock" : [ { "warehouse" : "B", "qty" : 15 }, { "warehouse" : "C", "qty" : 35 } ] }
{ "_id" : ObjectId("5911ce948c302726ff998858"), "item" : "journal", "instock" : [ { "warehouse" : "A", "qty" : 5 } ] }

查询1:

 > db.inventory.find( { "instock": { $elemMatch: { qty: 5, warehouse: "A" }}} )

输出:

{ "_id" : ObjectId("5911ce218c302726ff998853"), "item" : "journal", "instock" : [ { "warehouse" : "A", "qty" : 5 }, { "warehouse" : "C", "qty" : 15 } ] }
{ "_id" : ObjectId("5911ce948c302726ff998858"), "item" : "journal",    "instock" : [ { "warehouse" : "A", "qty" : 5 } ] }

查询2:

> db.inventory.find( { "instock.qty": { $elemMatch: { $gt: 10, $lte: 20 } } } )

输出:

无输出

1 个答案:

答案 0 :(得分:1)

来自docs

  

$ elemMatch运算符匹配包含数组字段的文档   至少有一个元素匹配所有指定的查询   标准。

注意field应该是一个数组。

查询数组内嵌入字段qty的第二个查询的正确语法是

db.inventory.find( { "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } } )

您应该有一个类似下面的文档qty作为当前第二个查询返回结果的数组字段。

{ "item" : "journal", "instock" : [ { "qty" : [ 5, 15 ] }, { "warehouse" : "A", "qty" : 5 }, { "warehouse" : "C", "qty" : 15 }] }