插入測試數據
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" } )
