插入测试数据

db.inventory.insertMany( [
   { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
   { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
   { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
   { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
]);

后面的栗子都会用到这里的测试数据

 

精确匹配嵌套文档

> db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )
{ "_id" : ObjectId("60b5e622dd6e93ee8bf35a9d"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }

这种写法不仅需要嵌套文档的字段、值相同,字段顺序也得一致

db.inventory.find(  { size: { w: 21, h: 14, uom: "cm" } }  )

换了个字段顺序就查不到同一条文档了

 

查询嵌套字段

要在嵌入/嵌套文档中的字段上指定查询条件,语法格式如下

"field.nestedField"

跟 JSON 取值一样,用 . 来找下一级的字段

 

栗子一:嵌套字段等于操作

> db.inventory.find( { "size.uom": "in" } )
{ "_id" : ObjectId("60b5e622dd6e93ee8bf35a9e"), "item" : "notebook", "qty" : 50, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "A" }
{ "_id" : ObjectId("60b5e622dd6e93ee8bf35a9f"), "item" : "paper", "qty" : 100, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "D" } 

size 字段值是一个文档,找到嵌套文档的 h 字段值等于 in 的所有文档

 

栗子二:嵌套字段结合单个查询条件操作符

> db.inventory.find( { "size.h": { $lt: 15 } } )
{ "_id" : ObjectId("60b5e622dd6e93ee8bf35a9d"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }
{ "_id" : ObjectId("60b5e622dd6e93ee8bf35a9e"), "item" : "notebook", "qty" : 50, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "A" }
{ "_id" : ObjectId("60b5e622dd6e93ee8bf35a9f"), "item" : "paper", "qty" : 100, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "D" }
{ "_id" : ObjectId("60b5e622dd6e93ee8bf35aa1"), "item" : "postcard", "qty" : 45, "size" : { "h" : 10, "w" : 15.25, "uom" : "cm" }, "status" : "A" }

size 字段值是一个文档,找到嵌套文档的 h 字段值小于 15 的所有文档

 

栗子三:多个不同嵌套字段结合 and 操作

> db.inventory.find( { "size.h": { $lt: 15 }, "size.uom": "in", status: "D" } )
{ "_id" : ObjectId("60b5e622dd6e93ee8bf35a9f"), "item" : "paper", "qty" : 100, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "D" }

三个条件必须同时满足

  • size 字段,嵌套文档的 h 字段值小于 15
  • size 字段,嵌套文档的 uom 字段值等于 in
  • status 字段值等于 D

 

重点

如果是指定单个字段的时候,可以不需要加 ""(当然,加了也无妨),比如

db.inventory.find( { status: "D" } )

 

如果是指定嵌套字段,必须加 "" ,比如上面的栗子

db.inventory.find( { "size.uom": "in" } )