gpt4 book ai didi

mongodb - 通过 _id 在 mongodb 数据库中的对象数组上查找

转载 作者:可可西里 更新时间:2023-11-01 10:39:53 26 4
gpt4 key购买 nike

我正在尝试在对象数组中查找对象的 ID。该 _id 与文档中的其他字段具有相同的字段名称 _id。这是我的模型(简要)

var CardSchema = new mongoose.Schema({
beName: String,
beLink: String,
cards: [{
cardType: String,
cardBundle: String
}]

这是我的数据库内容的示例

_id: ObjectId(5a52540638086448bf4235e8)
beName: Name1
beLink: Link1
cards: Array
0: Object
cardType: type1
cardBundle: 1
_id: ObjectId(5a526749d0ddab4bcdcc1556)
1: Object
cardType: type2
cardBundle: 1
_id: ObjectId(5a526749d0ddab4bcdcc1557)

...

_id: ObjectId(5a52540638086448bf4235e9)
beName: Namex
beLink: Linkx
cards: Array
0: Object
cardType: typex
cardBundle: x
_id: ObjectId(5a526749d0ddab4bcdcc1598)
1: Object
cardType: type2
cardBundle: 1
_id: ObjectId(5a526749d0ddab4bcdcc1599)

我正在尝试像这样查找特定卡的 ID

Cards.find({ _id: req.params.id}, function (err, post) {
if (err) return next(err);
res.json(post);
});

但是我得到一个空的结果

我也试过

Cards.find({ _id: new ObjectId(req.params.id)}...

最佳答案

您可能需要使用 aggregate功能$unwind根据 _id 查找匹配卡片的卡片数组.

所以,用 Mongoose 代替 find使用 aggregate流水线

示例文档

> db.cards.findOne()
{
"_id" : ObjectId("5a52f4136fe82b42b7439a21"),
"beName" : "Name1",
"beLink" : "Link1",
"cards" : [
{
"cardType" : "type1",
"cardBundle" : 1,
"_id" : "5a52f3a66f112b42b7439a20"
},
{
"cardType" : "type2",
"cardBundle" : 1,
"_id" : "5a52f3a66f112b42b7439a21"
}
]
}

聚合函数

> db.cards.aggregate([{$unwind: "$cards"}, {$match:{"cards._id" : "5a52f3a66f112b42b7439a20"}}] )

结果文档

> db.cards.aggregate([{$unwind: "$cards"}, {$match:{"cards._id" : "5a52f3a66f112b42b7439a20"}}] ).pretty()
{
"_id" : ObjectId("5a52f4136fe82b42b7439a21"),
"beName" : "Name1",
"beLink" : "Link1",
"cards" : {
"cardType" : "type1",
"cardBundle" : 1,
"_id" : "5a52f3a66f112b42b7439a20"
}
}
>

如果你知道父_id,你可以进一步优化它, 在聚合管道中 $match由家长_id , 然后 $unwind , 然后 $match在阵列卡上 _id

> db.cards.aggregate([{$match:{"_id":ObjectId("5a52f4136fe82b42b7439a21")}},{$unwind: "$cards"}, {$match:{"cards._id" : "5a52f3a66f112b42b7439a20"}}] )

关于mongodb - 通过 _id 在 mongodb 数据库中的对象数组上查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48144183/

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