elemMatch与Mongoose中的其他查询字段组合 [英] elemMatch combined with other query fields in 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"
}
}]
}]
我想使用节点中的猫鼬为给定的PatientId('123')仅获取活动的(状态为'A')嵌入式文档(饮食文档).
I wanted to fetch only active (status 'A') embedded document (diet document) for a given patientId ('123') using mongoose in node.
这是我的猫鼬查询:
query.where('patientId', 123)
.where('diet').elemMatch(function(elem) {
elem.where('_id', 1)
elem.where('status', 'A')
})
下面的查询生成了猫鼬,该查询为患者带来了嵌入式阵列饮食中的所有元素.
Mongoose generated below query, which is brining all elements from embedded array diet for patient.
Mongoose: patients.find({ diet: { '$elemMatch': { _id: '1', status: 'A' } }, patientId: '123' })
上面的查询也会获取所有子文档,而与Mongo Shell的状态无关.
The above query fetches all sub documents irrespective of status at Mongo Shell too.
它们唯一的方式是通过包装条件{'patientId':'123'},{'diet':{$ elemMatch:{'status':'A'}}}来使它在Mongo shell上起作用.
They only way I could make it work at Mongo shell by wrapping each where condition {'patientId':'123'},{'diet' : { $elemMatch : {'status':'A'} }}.
db.patients.find({'patientId':'123'},{'diet' : { $elemMatch : {'status':'A'} }} ).pretty() // works fine
如何强制猫鼬将每个查询字段括在花括号或其他任何想法中?
How can I force Mongoose to enclose each query field in a curly braces or any other thoughts?
推荐答案
在可行的查询中,$elemMatch
对象不是另一个查询条件,而是find
的输出字段选择(即投影)参数.
In your query that works, the $elemMatch
object is not another query condition, but is the output field selection (i.e. projection) parameter to find
.
要在Mongoose中执行相同的操作,您需要执行以下操作:
To do the same in Mongoose, you'd do something like:
PatientsModel.find({patientId: '123'}, {diet: {$elemMatch: {'status': 'A'}}}, cb)
OR
PatientsModel
.where('patientId', '123')
.select({diet: {$elemMatch: {'status': 'A'}})
.exec(cb);
这篇关于elemMatch与Mongoose中的其他查询字段组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!