Query on Embedded/Nested Documents
This page provides examples of query operations on embedded/nested documents using the db.collection.find()
method in mongosh
.
The examples on this page use the inventory
collection. Connect to a test database in your MongoDB instance then create the inventory
collection:
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" } |
]); |
Match an Embedded/Nested Document
To specify an equality condition on a field that is an embedded/nested document, use the query filter document { <field>: <value> }
where <value>
is the document to match.
For example, the following query selects all documents where the field size
equals the document { h: 14, w: 21, uom: "cm" }
:
db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } ) |
Equality matches on the whole embedded document require an exact match of the specified <value>
document, including the field order. For example, the following query does not match any documents in the inventory
collection:
db.inventory.find( { size: { w: 21, h: 14, uom: "cm" } } ) |
Query on Nested Field
To specify a query condition on fields in an embedded/nested document, use dot notation ("field.nestedField"
).
NOTE
When querying using dot notation, the field and nested field must be inside quotation marks.
Specify Equality Match on a Nested Field
The following example selects all documents where the field uom
nested in the size
field equals "in"
:
db.inventory.find( { "size.uom": "in" } ) |
Specify Match using Query Operator
A query filter document can use the query operators to specify conditions in the following form:
{ <field1>: { <operator1>: <value1> }, ... } |
The following query uses the less than operator ($lt
) on the field h
embedded in the size
field:
db.inventory.find( { "size.h": { $lt: 15 } } ) |
Specify AND
Condition
The following query selects all documents where the nested field h
is less than 15
, the nested field uom
equals "in"
, and the status
field equals "D"
:
db.inventory.find( { "size.h": { $lt: 15 }, "size.uom": "in", status: "D" } ) |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
2015-08-12 美国L1签证申请的常见问题解析
2015-08-12 美国L1签证面谈的时候一般VO会问到什么问题?
2015-08-12 美国L-1A签证简介
2015-08-12 想去美国?看完会成功率飙升的美国签证面试技巧
2015-08-12 程序员面试揭秘之程序员靠什么途径去美国工作?
2015-08-12 国签证面试时的注意事项
2015-08-12 nearly,about,almost的区别