mongodb - elemMatch 结合 Mongoose 中的其他查询字段

标签 mongodb mongoose

示例数据:

[{
    "_id": "529532bee0ea703842000003",
    "patientId": "123",
    "name": {
        "firstName": "John",
        "family": "Smith"
    },
    "diet": [{
        "_id": "1",
        "mealtType": "Break Fast",
        "timeofMeal": "2013-11-12T03:05:06.000Z",
        "status": "I",
        "calorie": {
            "value": 500,
            "unit": "cals"
        }
    },
    {
        "_id": "1",
        "mealtType": "Break Fast",
        "timeofMeal": "2013-11-12T03:05:06.000Z",
        "status": "A",
        "calorie": {
            "value": 550,
            "unit": "cals"
        }
    }]
}]

我想在节点中使用 mongoose 为给定的 patientId ('123') 仅获取事件的(状态'A')嵌入式文档(饮食文档)。

这是我的 Mongoose 查询:

query.where('patientId', 123)
     .where('diet').elemMatch(function(elem) {
    elem.where('_id', 1)
    elem.where('status', 'A')
})

Mongoose 生成以下查询,它正在为患者从嵌入式数组饮食中提取所有元素。

Mongoose: patients.find({ diet: { '$elemMatch': { _id: '1', status: 'A' } }, patientId: '123' })

上述查询也获取所有子文档,而不管 Mongo Shell 的状态。

只有这样,我才能通过包装每个 where 条件 {'patientId':'123'},{'diet' : { $elemMatch : {'status':'A'} }} 使其在 Mongo shell 中工作。

db.patients.find({'patientId':'123'},{'diet' : { $elemMatch : {'status':'A'} }} ).pretty() // works fine 

我如何强制 Mongoose 将每个查询字段括在大括号或任何其他想法中?

最佳答案

在您有效的查询中,$elemMatch 对象不是另一个查询条件,而是 find 的输出字段选择(即投影)参数。

要在 Mongoose 中执行相同的操作,您需要执行以下操作:

PatientsModel.find({patientId: '123'}, {diet: {$elemMatch: {'status': 'A'}}}, cb)

PatientsModel
    .where('patientId', '123')
    .select({diet: {$elemMatch: {'status': 'A'}})
    .exec(cb);

关于mongodb - elemMatch 结合 Mongoose 中的其他查询字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20383895/

相关文章:

node.js - MongoDB 和 i18n

javascript - Mongoose find() 不适用于 $not 查询

node.js - MongoDB 架构 : store id as FK or whole document

mongodb - 生成聚合结构

mongodb - 自定义反序列化

node.js - Node/ Mongoose - 错误 : Can't set headers after they are sent

Mongoose.js Doc Refs - 如何安全删除

node.js - 在大文档中查找对象

javascript - 在 js 类的异步函数中调用函数

php - UTCDateTime::toDateTime() 方法返回 1970 日期时间