在 mongodb 数据库中的对象数组中按 _id 查找

Find by _id on an array of objects in mongodb database

我正在尝试在对象数组中查找对象的 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)}...

尝试这样做:

const ObjectId = require("mongodb").ObjectID,

/* some other statements */

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

供参考:https://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html

您可能需要使用 aggregate 函数来 $unwind 卡片数组以根据 _id.

找到匹配的卡片

所以,在猫鼬中而不是 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,则可以进一步优化它,在父级 _id 的聚合管道 $match 中,然后是 $unwind,然后是 $match阵列卡上_id

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

问题有点含糊,但通过查看其他答案并在 url 中找到卡片的 _id,我猜你有卡片的 _id 并且你想找到父文档。如果是这样,那么您不需要聚合。查找查询完成工作:

db.cards.find({"cards._id": _id})