【问题标题】:elemMatch combined with other query fields in MongooseelemMatch 与 Mongoose 中的其他查询字段相结合
【发布时间】:2013-12-21 10:37:52
【问题描述】:

样本数据:

[{
    "_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')嵌入文档(饮食文档)。

这是我的猫鼬查询:

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 将每个查询字段括在花括号或任何其他想法中?

【问题讨论】:

  • 您到底想完成什么?这不是很清楚。本质上,您想知道如何编写一个 mongoose 查询来完成与 Query1 相同的事情?请说明您要退货的内容。
  • EmptyArsenal,我已经更新了我的帖子:我想使用 mongoose 为给定的 PatientId(根级别文档的搜索字段)仅获取活动(状态“A”)嵌入文档(饮食文档)节点。

标签: mongodb mongoose


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-16
    • 2014-06-09
    • 2017-01-11
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多