如何用 Mongoose 查找嵌套数组对象?

fae0ux8s  于 2023-01-31  发布在  Go
关注(0)|答案(1)|浏览(163)
[
  {
  _id: new ObjectId("63cc22dfe258792490ac0fb5"),
  categoryName: 'Rental Equipment',
  products: [
    {
      _id: new ObjectId("63ce9701ba256f972473cd6a"),
      partName: 'product one'
      partNumber: 'ym129150-35151'
    },
    {
      _id: new ObjectId("63ce2221207c858d01a3c8ac"),
      partName: 'product two',
      partNumber: 'ym129150-35151',
    }
  ]
},{
  _id: new ObjectId("63cc22dfe258792490ac0fb5"),
  categoryName: 'Engine Parts',
  products: [
    {
      _id: new ObjectId("23ce9701ba156f972473cd3a"),
      partName: 'product one'
      partNumber: 'ym129150-35151'
    },
    {
      _id: new ObjectId("73ce2221203c858d01a3c83b"),
      partName: 'product two',
      partNumber: 'ym129150-35151',
    }
  ]
}
]

我想找到特定的对象数组(产品),其中一个位于产品数组中。我试图找到对象数组,但它返回了产品_id所在的对象的整个集合。

const product = db.collection.find({
      products: {
        $elemMatch: {
          _id: "63ce9701ba256f972473cd6a",
        },
      },
    });

我希望从产品数组中查找特定对象。

输出将为:

{
   _id: new ObjectId("63ce9701ba256f972473cd6a"),
   partName: 'product one'
   partNumber: 'ym129150-35151'
}
33qvvth1

33qvvth11#

尝试使用聚合框架:

db.collection.aggregate([
  {
    "$unwind": "$products"
  },
  {
    "$match": {
      "products._id": "63ce9701ba256f972473cd6a",
      
    }
  },
  {
    "$project": {
      "_id": 0,
      "products._id": 1,
      "products.partName": 1,
      "products.partNumber": 1,
      
    }
  },
  {
    "$replaceRoot": {
      "newRoot": "$products"
    }
  }
])

去操场

相关问题