1. 程式人生 > >mongodb查詢嵌入/巢狀文件

mongodb查詢嵌入/巢狀文件

這裡演示如何使用:db.collection.find()方法對嵌入/巢狀文件的查詢操作的示例。 此頁面上的示例使用inventory集合。要填充庫存(inventory)集合以準備一些資料,請執行以下命令:

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" }
]);

Shell

匹配嵌入/巢狀文件

要在作為嵌入/巢狀文件的欄位上指定相等條件,請使用查詢過濾器文件{<field>:<value>},其中<value>是要匹配的文件。

例如,以下查詢選擇欄位size等於{ h: 14, w: 21, uom: "cm" }的所有文件:

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

Shell

整個嵌入式文件中的相等匹配需要精確匹配指定的<value>文件,包括欄位順序。
例如,以下查詢與庫存(inventory)集合中的任何文件不匹配:

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

Shell

查詢巢狀欄位

要在嵌入/巢狀文件中的欄位上指定查詢條件,請使用點符號(“field.nestedField”)。

在巢狀欄位上指定等於匹配

以下示例選擇在size欄位中巢狀的欄位uom等於“in”的所有文件:

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

nodejs查詢巢狀欄位.project(xxx) 

find.skip((page-1)*pageNum).sort(sort).limit(pageNum).project(whereN)