如何从数组中获取匹配对象的
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
方法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;
方法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];
方法3
与
pricing.$
一起返回第一个匹配元素。
let item = await Item.find({
_id: {
"$oid": "663a4dbb97674691089c835a"
},
pricing: {
$elemMatch: {
mrp: 100,
price: 100
}
}
},
{
"pricing.$": 1
});
let matchedId = item?.pricing[0]._id;