mongodb 中查询嵌入或多级文档

本文总结了如何在 mongoDB 中查询嵌入或多级文档(Embedded/Nested Document)。

集合数据

假设有如下文档,集合名称为 inventory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
db.collection('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'
}
]);

匹配整个子文档

使用 query filter document { <field>: <value> } 来匹配子文档。

例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 查询
db.inventory.find({
// size 只有整个对象完全匹配时,才返回,不支持多级嵌套匹配
size: { h: 14, w: 21, uom: 'cm' }
})

// 结果
{
"_id": ObjectId("6245387e951c0000ea00145b"),
"item": "journal",
"qty": 25,
"size": {
"h": 14,
"w": 21,
"uom": "cm"
},
"status": "A"
}

注意:

查询不支持多级嵌套匹配。size 只有整个对象完全匹配时,才返回。下面的查询的结果为空:

1
2
3
db.inventory.find({
size: { h: 8.5 }
})

匹配嵌套字段

使用 dot notation field.nestedField 来进行嵌套匹配查询。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
db.inventory.find({
"size.h": 10
})

// 返回结果
{
"_id": ObjectId("6245387e951c0000ea00145f"),
"item": "postcard",
"qty": 45,
"size": {
"h": 10,
"w": 15.25,
"uom": "cm"
},
"status": "A"
}

使用查询操作符匹配

在使用 query filter document 时,可以使用 query operators 来进行更复杂的查询。

格式:

1
{ <field1>: { <operator1>: <value1> }, ... }

查询示例:

1
2
3
4
5
db.inventory.find({
'size.h': { $lt: 15 },
'size.uom': 'in',
status: 'D'
})

其它

本文中提供的示例代码运行平台为 Navicat。在 nodejs 中也同样适用。

参考

  1. Query on Embedded/Nested Documents

  2. Query and Projection Operators — MongoDB Manual

  3. Dot Notation