首页 > 解决方案 > 如何通过猫鼬(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

标签: javascriptmongodbmongoosemongodb-queryaggregation-framework

解决方案


选项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"
    }
  }
])

推荐阅读