猫鼬在数组中查找子文档

时间:2020-01-09 19:32:58

标签: mongodb mongoose mongoose-schema

我在Robo3t中有以下数据 Mongo collection 使用此模型:

const eleccionSchema = new mongoose.Schema({
    e: [{
        id: {
            type: String,
            required: true
        },
        l:[...]
    }],
    eleccion: {
        type: Number,
        required: true,
        ref: 'Corte'
    }
})
//? Create the model
const Eleccion = mongoose.model('Eleccion', eleccionSchema)

现在我正试图像这样基于e.id获取一些数据

const eleccion = await Eleccion.findOne({'e.id':'A'})

但是它实际上是返回整个数组,而不只是返回一个 output

1 个答案:

答案 0 :(得分:1)

使用投影固定:https://docs.mongodb.com/manual/reference/operator/projection/elemMatch/

const eleccion = await Eleccion.findOne({}, {
 'e':
   { $elemMatch: { id: 'A' } }
})