在MongoDB中,可以使用elemMatch操作符来查询包含不同层级字段的文档。下面是一个使用elemMatch的代码示例:
// 假设有以下文档结构
/*
{
"_id": 1,
"name": "John",
"addresses": [
{
"street": "123 Main St",
"city": "New York",
"country": "USA"
},
{
"street": "456 Park Ave",
"city": "Los Angeles",
"country": "USA"
}
],
"orders": [
{
"orderNumber": 111,
"products": [
{
"name": "Product A",
"quantity": 2
},
{
"name": "Product B",
"quantity": 1
}
]
},
{
"orderNumber": 222,
"products": [
{
"name": "Product C",
"quantity": 3
},
{
"name": "Product D",
"quantity": 4
}
]
}
]
}
*/
// 查询包含特定城市的地址
db.collection.find({ addresses: { $elemMatch: { city: "New York" } } })
// 查询包含特定产品的订单
db.collection.find({ orders: { $elemMatch: { "products.name": "Product A" } } })
// 查询包含特定城市的地址并且包含特定产品的订单
db.collection.find({
addresses: { $elemMatch: { city: "New York" } },
orders: { $elemMatch: { "products.name": "Product A" } }
})
在上述示例中,我们使用了elemMatch操作符来查询包含特定城市的地址和包含特定产品的订单。注意,elemMatch操作符可以用于不同层级的字段查询,并且可以同时使用多个elemMatch操作符来构建更复杂的查询条件。
上一篇:不同层级的比例分布