MongoDB - 如何从数组中获取匹配对象的 id

问题描述 投票:0回答:1

如何从数组中获取匹配对象的

id
? 目前,我正在从
pricing
数组中获取所有 ID。

虽然我只想要匹配的那个。

await Item.find(
   {_id: "663a4dbb97674691089c835a", pricing: {$elemMatch: {mrp: 100, price: 100}}}, 
   {"pricing._id": 1})

MongoDB 文档:

{
  "_id": {
    "$oid": "663a4dbb97674691089c835a"
  },
  "desc": {
    "name": "BLA BLA",
  },
  "pricing": [
    {
      "firstAddedDate": "05/30/2024",
      "mrp": 100,
      "price": 100,
      "qty": 1,
      "_id": {
        "$oid": "66578e181df0f2a544263b2b"
      }
    },
    {
      "firstAddedDate": "05/30/2024",
      "mrp": 100,
      "price": 80,
      "qty": -1,
      "_id": {
        "$oid": "66580f3425b849794bb87bd7"
      }
    }
  ]
}

我想要的结果:

66578e181df0f2a544263b2b

node.js mongodb express mongodb-query
1个回答
1
投票

方法1

在投影中,您应该使用

$filter
运算符来过滤匹配元素。

let item = await Item.find({
  _id: new ObjectId("663a4dbb97674691089c835a"),
  pricing: {
    $elemMatch: {
      mrp: 100,
      price: 100
    }
  }
},
{
  "pricing": {
    $filter: {
      input: "$pricing",
      cond: {
        $and: [
          {
            $eq: [
              "$$this.mrp",
              100
            ]
          },
          {
            $eq: [
              "$$this.price",
              100
            ]
          }
        ]
      }
    }
  }
});

let matchedId = item?.pricing[0]._id;

演示方法 1 @ Mongo Playground


方法2

您可以与

$map
一起返回匹配的
_id

let item = await Item.find({
  _id: new ObjectId("663a4dbb97674691089c835a"),
  pricing: {
    $elemMatch: {
      mrp: 100,
      price: 100
    }
  }
},
{
  "pricing": {
    $map: {
      input: {
        $filter: {
          input: "$pricing",
          cond: {
            $and: [
              {
                $eq: [
                  "$$this.mrp",
                  100
                ]
              },
              {
                $eq: [
                  "$$this.price",
                  100
                ]
              }
            ]
          }
        }
      },
      in: "$$this._id"
    }
  }
});

let matchedId = item?.pricing[0];

演示方法 2 @ Mongo Playground


方法3

pricing.$
一起返回第一个匹配元素。

let item = await Item.find({
  _id: {
    "$oid": "663a4dbb97674691089c835a"
  },
  pricing: {
    $elemMatch: {
      mrp: 100,
      price: 100
    }
  }
},
{
  "pricing.$": 1
});

let matchedId = item?.pricing[0]._id;

演示方法 3 @ Mongo Playground

© www.soinside.com 2019 - 2024. All rights reserved.