mongodb - 如何从对象数组中返回匹配的文档
问题描述
我正在尝试根据价格从产品集合中过滤产品。
当前产品系列:
[
{
_id: ObjectId("56f277b1279871c20b8b4566"),
product_name:'sample product 1',
product_items:[
{
product_price: 50.99,
product_item_no: '123456789',
product_images:['default.png']
},
{
product_price: 11.99,
product_item_no: '683456789',
product_images:['default2.png']
}
],
product_status_is_active: true,
},
{
_id: ObjectId("56f277b1279871c20b8b4567"),
product_name:'sample product 2',
product_items:[
{
product_price: 12.99,
product_item_no: '45678923',
product_images:['default2.png']
},
{
product_price: 66.99,
product_item_no: '683456789',
product_images:['default4.png']
}
],
product_status_is_active: true,
}
]
猫鼬查询:
{
'$match': {
product_status_is_active: true,
product_items: { '$elemMatch': { product_price: { '$gte': 60, '$lte': 100 } } }
}
},
电流输出:
{
_id: ObjectId("56f277b1279871c20b8b4567"),
product_name:'sample product 2',
product_items:[
{ // This object should not display
product_price: 12.99,
product_item_no: '45678923',
product_images:['default2.png']
},
{
product_price: 66.99,
product_item_no: '683456789',
product_images:['default4.png']
}
],
product_status_is_active: true,
}
期望输出如下:
{
_id: ObjectId("56f277b1279871c20b8b4567"),
product_name:'sample product 2',
product_items:[
{
product_price: 66.99,
product_item_no: '683456789',
product_images:['default4.png']
}
],
product_status_is_active: true,
}
但是我的查询的输出也包含不匹配的 product_price。
如何强制 MongoDB 只返回与我的查询匹配的 product_price?
问候和感谢。
解决方案
您可以通过聚合来实现这一点。
- 匹配
product_status_is_active:true
- 用于
$filter
根据条件过滤数组 - 将老化匹配到空
product_items
数组
聚合阶段是
[
{
$match: {
"product_status_is_active": true
}
},
{
$addFields: {
product_items: {
$filter: {
input: "$product_items",
cond: {
$and: [
{
$gte: [
"$$this.product_price",
60
]
},
{
$lte: [
"$$this.product_price",
100
]
}
]
}
}
}
}
},
{
$match: {
product_items: {
$ne: []
}
}
}
]
工作Mongo游乐场
推荐阅读
- spring-boot-actuator - 动态代码评估:不安全的反序列化(Spring Boot 2) - 如何避免与执行器相关的强化问题,还是误报?
- angular - 如果数据未以角度 6 加载,如何设置页面样式
- c++ - 编译器错误:析构函数的抛出说明符更宽松
- visual-studio-code - 在 Windows 中从命令行打开 Visual Studio Code
- javascript - 如何使用 chartist js 在同一个图表中相对拉伸具有不同数量索引的两个系列?
- python - Pandas 数据帧到内存中的镶木地板缓冲区
- c# - 如何在 FormFlow 中的消息到达识别器之前拦截它?(枚举使用)
- kubernetes - 在 Kubernetes 中同时运行多个 pod 需要大量时间
- testing - XSL 测试错误至少包含一个而不是仅包含一个
- javascript - 如何使用 d3 仅在 y 轴上添加鼠标放大?