我有以下格式的mongodb文档:
{
"date": "04-10-2018",
"botData": [{
"botId": "botId1",
"date": "04-10-2018",
"weekDay": "Thursday",
"hourOfDayData": {
"09": 24,
"11": 56,
"02": 66
},
"channelData": [{
"channel": "web",
"totalTraffic": 185,
"totalMessagesSent": 357,
"avgMessagesSentPerSession": 1.93,
"averageInteractionTime": 4.34
},
{
"channel": "fb",
"totalTraffic": 32,
"totalMessagesSent": 78,
"avgMessagesSentPerSession": 1.93,
"averageInteractionTime": 2.34
}
]
}, {
"botId": "botId2",
"date": "04-10-2018",
"weekDay": "Thursday",
"hourOfDayData": {
"09": 24,
"11": 56,
"02": 66
},
"channelData": [{
"channel": "web",
"totalTraffic": 185,
"totalMessagesSent": 357,
"avgMessagesSentPerSession": 1.93,
"averageInteractionTime": 4.34
},
{
"channel": "fb",
"totalTraffic": 32,
"totalMessagesSent": 78,
"avgMessagesSentPerSession": 1.93,
"averageInteractionTime": 2.34
}
]
}]}
我想查询文档的一部分。我想要一个查询,它将给我以下结果:
{
"botId": "botId1",
"date": "04-10-2018",
"weekDay": "Thursday",
"hourOfDayData": {
"09": 24,
"11": 56,
"02": 66
},
"channelData": [{
"channel": "web",
"totalTraffic": 185,
"totalMessagesSent": 357,
"avgMessagesSentPerSession": 1.93,
"averageInteractionTime": 4.34
},
{
"channel": "fb",
"totalTraffic": 32,
"totalMessagesSent": 78,
"avgMessagesSentPerSession": 1.93,
"averageInteractionTime": 2.34
}
]
}
这是我现在正在使用的查询:
db.test.find({botData:{$elemMatch:{botId:'botId1'}}},{"botData":1,_id:0})
我得到以下结果:
{
"botData" : [
{
"botId" : "botId1",
"date" : "04-10-2018",
"weekDay" : "Thursday",
"channelData" : [
{
"channel" : "web",
"totalTraffic" : 185.0,
"totalMessagesSent" : 357.0,
"avgMessagesSentPerSession" : 1.93,
"averageInteractionTime" : 4.34
},
{
"channel" : "fb",
"totalTraffic" : 32.0,
"totalMessagesSent" : 78.0,
"avgMessagesSentPerSession" : 1.93,
"averageInteractionTime" : 2.34
}
]
},
{
"botId" : "botId2",
"channelData" : [
{
"channel" : "web",
"totalTraffic" : 185.0,
"totalMessagesSent" : 357.0,
"avgMessagesSentPerSession" : 1.93,
"averageInteractionTime" : 4.34
},
{
"channel" : "fb",
"totalTraffic" : 32.0,
"totalMessagesSent" : 78.0,
"avgMessagesSentPerSession" : 1.93,
"averageInteractionTime" : 2.34
}
]
}
]
}
您已经看到,我已经尝试过mongodb投影功能。但这没有按我想要的那样工作。
任何人都可以找到合适的查询以获得我想要的结果吗?
答案 0 :(得分:1)
您可以尝试以下汇总
db.collection.aggregate([
{ "$match": { "botData.botId": "botId1" }},
{ "$addFields": {
"botData": {
"$filter": {
"input": "$botData",
"cond": { "$eq": ["$$this.botId", "botId1"] }
}
}
}},
{ "$unwind": "$botData" },
{ "$replaceRoot": { "newRoot": "$botData" }}
])
或
db.collection.aggregate([
{ "$match": { "botData.botId": "botId1" }},
{ "$unwind": "$botData" },
{ "$match": { "botData.botId": "botId1" }},
{ "$replaceRoot": { "newRoot": "$botData" }}
])