gpt4 book ai didi

javascript - Mongoose 从查询中检索特定的数组索引(不是完整的数组)

转载 作者:行者123 更新时间:2023-12-03 01:21:32 26 4
gpt4 key购买 nike

考虑以下集合:

       > db.customers.find().pretty();

{
"_id" : ObjectId("5b675d8180db9c13ac5b5c16"),
"name" : "John",
"active": true,
"purchasedItems" : [
{
"item_id" : "5b639e2dbc55ef13a6e50d29",
"quantity" : 2,
"deliveryDate" : 1536095404603
},
{
"item_id" : "5b0f0dcc4d122607cff6ce87",
"quantity" : 33,
"deliveryDate" : 1536179151868
},
{
"item_id" : "5b3a74bd973d5014df9d7d4b",
"quantity" : 23,
"deliveryDate" : 1536265571029
},
{
"item_id" : "5b101be68244dd03fb64acdd",
"quantity" : 111,
"deliveryDate" : 1536351973191
},
{
"item_id" : "5b101be68244dd03fb64acdd",
"quantity" : 11,
"deliveryDate" : 1536092750426
}
]
},
{
"_id" : ObjectId("5b675d8180db9c13ac5b5c16"),
"name" : "John",
"active": true,
"purchasedItems" : [
{
"item_id" : "354639e2dbc55ef13a6e50d29",
"quantity" : 1,
"deliveryDate" : 1536095404603
},
{
"item_id" : "53340dcc4d122607cff6ce87",
"quantity" : 12,
"deliveryDate" : 1536179151868
},
{
"item_id" : "5b7654bd973d5014df9d7d4b",
"quantity" : 44,
"deliveryDate" : 1536265571029
},
{
"item_id" : "5b1014648244dd03fb64acdd",
"quantity" : 14,
"deliveryDate" : 1536351973191
},
{
"item_id" : "5b101be34344dd03fb64acdd",
"quantity" : 6,
"deliveryDate" : 1536092750426
}
]
}

如何检索查询中的第 n 个 purchasedItems 元素而不返回完整的 purchasedItems 数组?

我尝试过但没有成功(考虑到 index 是我想要检索的数组索引):

CustomerModel.findOne(
{
_id: customer_id,
active: true
},
{
$arrayElementAt: { purchasedItems: index }
}
)

错误:

Error: error: {
"ok" : 0,
"errmsg" : "Unsupported projection option: $arrayElementAt: { purchasedItems: 1.0 }",
"code" : 2,
"codeName" : "BadValue"
}

最佳答案

$arrayElemAt 应该与 $aggregation 管道一起使用。要检索第 n 个购买项目,请查看下面的聚合代码。

db.test.aggregate([{
"$match": {
_id: customer_id,
active: true
}
},
{
"$project": {
_id: 1,
name: 1,
purchasedItems: { $arrayElemAt: ["$purchasedItems", INDEX]}
}
}
])

这将返回具有以下结构的文档

{ 
"_id" : ObjectId("5b6b2672d99b3f60dfd39e6b"),
"name" : "John",
"purchasedItems" : { "item_id" : "5b3a74bd973d5014df9d7d4b", "quantity" : 23, "deliveryDate" : 1536265571029 }
}

关于javascript - Mongoose 从查询中检索特定的数组索引(不是完整的数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51752021/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com