javascript - 如何通过猫鼬(javascript)中的多个值查询数组内的对象?
问题描述
我有一个对象,服务器将收到 auser_id
和 a part_id
。我需要获取特定用户,然后通过提供的部件 ID 过滤部件并获取价格。
{ _id: 6086b8eec1f5325278846983, user_id: '13', car_name: '车名 1', created_at: 2008-11-25T00:46:52.000Z, 部分: [ { _id: 6086ee212681320190c3c8e0, part_id: 'P456', part_name: '零件名称 1', image: '图片网址', 统计:{ 价格:10, } }, { _id: 6087e7795e2ca925fc6ead27, part_id: 'P905', part_name: '零件名称 2', image: '图片网址', 统计:{ 价格:15, } } ] }
我尝试运行以下命令,但忽略了part_id
过滤器并返回数组中的每个部分。
Custumers.findOne({'user_id': '13', 'parts.part_id': 'P456'})
也尝试了聚合但仍然没有运气。
Customers.aggregate([
{ $match: { 'user_id': '13'}}
]).unwind('parts')
我检查了 mongoose 文档,但无法理解它。请让我知道我错过了什么。
猫鼬版本:5.12.4
解决方案
选项1
如果您只有 1 个匹配的零件,这将起作用
$ 运算符根据查询语句中的某些条件投影集合中每个文档的第一个匹配数组元素。
演示 - https://mongoplayground.net/p/tgFL01fK3Te
db.collection.find(
{ "user_id": "13", "parts.part_id": "P456" },
{ "parts.$": 1, car_name: 1 } // add fields you need to projection
)
选项-2
演示 - https://mongoplayground.net/p/_PeP0WHVpJH
db.collection.aggregate([
{
$match: {
"user_id": "13",
"parts.part_id": "P456"
}
},
{
$unwind: "$parts" // break into individual documents
},
{
$match: {
"parts.part_id": "P456"
}
}
])
推荐阅读
- html - 尝试使用 VBA 更改值时未在 IE 中更新值
- javascript - 如何在 Javascript 上解析这个 JSON
- php - 带有来自 sql 数据库的值的表没有出现
- reactjs - 我如何让父母身高增加?
- c++ - 放在堆上的数组中的堆栈上的值会发生什么
- ios - 敲击时键盘打不开
- java - Java:有没有办法运行一个类的方法来初始化我想要运行它的类的实例?
- vb.net - 线程内部模块并将值添加到 me.texbox1
- r - 如何将从 pdf 文件中提取的日期与使用 R 从中提取的数据相关联?
- typescript - 如何获取创建的文档云函数 Typescript 的 id