【问题标题】:mongoose find collection by _id in a list of array猫鼬在数组列表中按_id查找集合
【发布时间】:2020-06-03 08:49:57
【问题描述】:

这是我的架构

var PositiveSchema = new mongoose.Schema({
    schoolID: {
        type: mongoose.Schema.Types.ObjectId, ref: 'School'
    },
    name: String,
    restrictAwardTo: Object
})

现在restrictAwardTo 以这种格式保存数据

"restrictAwardTo" : [ 
        {
            "_id" : "5c31907d908eb8404657cbf0",
            "firstName" : "Admin 2a"
        }, 
        {
            "_id" : "5c1a7677c98da061141475a8",
            "firstName" : "Justice"
        }, 
        {
            "_id" : "5c1a7677c98da061141475a9",
            "firstName" : "Itik"
        }
    ],

如何使用restrictAwardTo 下列出的_id 之一在我的文档中进行搜索?我尝试了下面给出的解决方案

更新:在 Robo3t 中,此查询 db.getCollection('positives').find({ 'restrictAwardTo._id' : {$in: ['5c1a7677c98da061141475a7']} }) 有效。现在我也让它适用于猫鼬。

【问题讨论】:

  • 您能否添加完整的示例输入文档和 JSON 格式的预期输出?

标签: mongodb mongoose


【解决方案1】:

这是适合我的猫鼬:

Positive.find({ schoolID:  mongoose.mongo.ObjectId(schoolID), "restrictAwardTo._id": { $in: [userID]} })

但我不完全确定大型记录的性能。

【讨论】:

    【解决方案2】:

    你可以通过这种方式。

    Positive.findOne({'restrictAwardTo': {$elemMatch: {_id: userID}}}, 
            (err,schoolInfo) => { });
    

    【讨论】:

      猜你喜欢
      • 2021-09-03
      • 2017-03-28
      • 2020-09-12
      • 2021-05-06
      • 2017-04-06
      • 2016-05-14
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多