[英]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.