![](/img/trans.png)
[英]Query an array of sub-documents where a field's value is same for all elements
[英]How to query by a field in an array of sub-documents with greater than condition?
data: [
{
"_id" : ObjectId("5ebda923a52984db48ab45f6"),
"detectorid" : 1371,
"loopdata" : [
{
"starttime" : "9/15/2011 0:00:00",
"volume" : 2,
"speed" : 65,
"occupancy" : 2,
"status" : 2,
"dqflags" : 0
},
{
"starttime" : "9/15/2011 0:00:20",
"volume" : 2,
"speed" : 53,
"occupancy" : 2,
"status" : 2,
"dqflags" : 0
},
{
"starttime" : "9/15/2011 0:00:40",
"volume" : 0,
"speed" : "",
"occupancy" : 0,
"status" : 0,
"dqflags" : 0
}
]
大家好,这是我收藏的数据。 我想返回速度超过53。我试过了db.collection.find({"data.speed":{$gt:53}})
它返回了错误的结果(基本上返回了所有内容),我不知道我错了什么。 有什么提示吗? 谢谢
我给你做了两个解决方案:
speeds
字段和_id
文档,这可以解决问题:询问:
db.collection.aggregate([
// $filter will apply the condition to every element of the array
// in this case the array is [65, 53 ""]
{
$project: {
"speeds": {
$filter: {
"input": "$loopdata.speed",
"as": "speed",
"cond": {
$and: [
{
$eq: [
{
$type: "$$speed" // check if the type is numeric
},
"double"
]
},
{
$gt: [
"$$speed", // check if it's greater than 53
53
]
}
]
}
}
}
}
}
])
结果:
[
{
"_id": ObjectId("5ebda923a52984db48ab45f6"),
"speeds": [
65
]
}
]
loopdata
,那么这可以解决问题:查询 2:
db.collection.aggregate([
{
$addFields: {
"loopdata": {
$filter: {
"input": "$loopdata",
"as": "data",
"cond": {
$and: [
{
$eq: [
{
$type: "$$data.speed"
},
"double"
]
},
{
$gt: [
"$$data.speed",
53
]
}
]
}
}
}
}
}
])
结果:
[
{
"_id": ObjectId("5ebda923a52984db48ab45f6"),
"detectorid": 1371,
"loopdata": [
{
"dqflags": 0,
"occupancy": 2,
"speed": 65,
"starttime": "9/15/2011 0:00:00",
"status": 2,
"volume": 2
}
]
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.