目前,我正在為 MongoDB 檔案系統的作業方式而苦苦掙扎。我想使用自動生成的 id 獲取陣列元素,但如何獲取我不知道的特定資料。
我當前的架構是
const ItemPricesSchema = new mongoose.Schema({
_id : {
type: String
},
ItemsPrices: {
type: [{
barcode : {
type: String
},
itemName : {
type: String
},
price : {
type: String
}
}]
}
});
當前資料以這種方式存盤
{
"_id": "[email protected]",
"ItemsPrices": [
{
"barcode": "345345",
"itemName": "maggie",
"price": "45",
"_id": "620a971e11120abbde5f4c3a"
},
{
"barcode": "356345",
"itemName": "monster",
"price": "70",
"_id": "620a971e11120abbde5f4c3b"
}
],
"__v": 0
}
我想要實作的是我想通過ids找到陣列元素
如果我想要一個 id 為“620a971e11120abbde5f4c3b”的特定陣列元素,我該怎么辦?我試過 $unwind , $in, $match ...
結果應該像
{
"_id": "[email protected]",
"ItemsPrices": [
{
"barcode": "356345",
"itemName": "monster",
"price": "70",
"_id": "620a971e11120abbde5f4c3b"
}
],
"__v": 0
}
我嘗試的答案是這樣的
router.get('/filter/:id', async (req, res) => {
try {
const item = await ItemPricesSchema.aggregate([
{$project: {
"ItemsPrices": {
$filter: {
input: "$ItemsPrices",
as: "item",
cond: {
$eq: [
"$$item._id",
"620a8dd1c88ae3eb88a8107a"
]
}
}
}
}
}
])
res.json(item);
console.log(item);
} catch (error) {
res.status(500).json({message: error.message});
}
})
并回傳類似這樣的東西(空陣列)
[
{
"_id": "[email protected]",
"ItemsPrices": []
},
{
"_id": "[email protected]",
"ItemsPrices: []
},
{
"_id": "asd@asd.asd",
"ItemsPrices": []
},
{
"_id": "qwe@qwe.qwe",
"ItemsPrices": []
}
]
但如果我搜索價格 $$item.price
cond: {
$eq: [
"$$item.price",
"30"
]
}
它回傳完美的輸出
[
{
"_id": "[email protected]",
"ItemsPrices": []
},
{
"_id": "[email protected]",
"ItemsPrices: []
},
{
"_id": "asd@asd.asd",
"ItemsPrices": []
},
{
"_id": "qwe@qwe.qwe",
"ItemsPrices": [
{
"barcode":"234456345",
"price":"30",
"itemName":"monster",
"_id":"620a8dd1c88ae3eb88a8107a"
}
]
}
]
uj5u.com熱心網友回復:
您可以對陣列部分進行聚合$project和應用。$filter在貓鼬中,您可以以或多或少類似的方式應用聚合查詢https://mongoosejs.com/docs/api/aggregate.html
db.collection.aggregate([
{
$project: {
"ItemsPrices": {
$filter: {
input: "$ItemsPrices",
as: "item",
cond: {
$eq: [
"$$item._id",
mongoose.Types.ObjectId("620a971e11120abbde5f4c3b")
]
}
}
},
"__v": 1 //when projecting 1 means in the final result this field appears
}
}
])
更多示例
演示
uj5u.com熱心網友回復:
選項1:
如cmgchess$filter所述,在聚合查詢中使用
選項 2:
如果您只想要陣列中的一個物件,您可以像這樣使用$elemMatch:
db.collection.find({
"ItemsPrices._id": "620a971e11120abbde5f4c3b"
},
{
"ItemsPrices": {
"$elemMatch": {
"_id": "620a971e11120abbde5f4c3b"
}
}
})
這里的例子
但請注意,$elemMatch僅回傳第一個元素。檢查另一個示例,其中有兩個具有所需_id但僅回傳一個的物件。
如前所述,如果您只有一個(或僅存在一個),也許您可??以使用find并$elemMatch避免整個陣列的過濾器。但是如果可以是多個值,請使用$filter.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/423992.html
標籤:javascript 数组 json mongodb 猫鼬
