Mongodb 检索动态子文档密钥
我有这个mongo文件Mongodb 检索动态子文档密钥,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,我有这个mongo文件 { "name": "aaa", "Time": "Now", "_id": "656i9gfk543klffx", "lastReadings": { "7-Temperature": { "_t": "NumberReading", "timestamp": "2017-02-13T12:51:50.000+0000", "unit": "C",
{
"name": "aaa",
"Time": "Now",
"_id": "656i9gfk543klffx",
"lastReadings": {
"7-Temperature": {
"_t": "NumberReading",
"timestamp": "2017-02-13T12:51:50.000+0000",
"unit": "C",
"typeCode": 7,
"name": "Temperature",
"numberValue": 11.271406207825713
},
"30-DISCONNECT": {
"_t": "NumberReading",
"internalTimestamp": "2017-06-02T19:16:33.050+0000",
"timestamp": "2017-06-02T19:16:27.147+0000",
"unit": "",
"typeCode": 30,
"name": "DISCONNECT",
"numberValue": 1
}
}
},
{
"name": "aaa",
"Time": "Now",
"_id": "gtrg565opgf0",
"lastReadings": {
"7-Temperature": {
"_t": "NumberReading",
"timestamp": "2017-02-13T12:51:50.000+0000",
"unit": "C",
"typeCode": 7,
"name": "Temperature",
"numberValue": 46
},
"25-Water": {
"_t": "NumberReading",
"internalTimestamp": "2017-06-02T19:16:33.050+0000",
"timestamp": "2017-06-02T19:16:27.147+0000",
"unit": "",
"typeCode": 25,
"name": "Water",
"numberValue": 1
}
}
}
我试图从“LastReaders”对象中获取不同的字段键,其中“name”字段等于“aaa”。
因此,我预期的结果将是:
["7-Temperature", "30-DISCONNECT","25-Water"]
“lastReadings”中的子对象键是动态的,我不知道它们的名称以及“lastReadings”中有多少个文件
我可以通过什么聚合查询来实现此结果
我已经回答了这个问题:
{$match: {"name":"aaa"}},
{ $group: { _id: "name", mergedEvents: { $mergeObjects: "$lastReadings" } } }
但是当我有很多文档时,它似乎运行得很慢(在“LastReads”上建立索引会提高性能吗?),并且它会返回整个不必要的对象
谢谢。好吧,我们可以通过以下管道来实现这一点:
[
{
"$group":{
"_id":null,
"lastReadings":{
"$push":{
"$map":{
"input":{
"$objectToArray":"$lastReadings"
},
"in":"$$this.k"
}
}
}
}
},
{
"$project":{
"mergeEvent":{
"$reduce":{
"input":"$lastReadings",
"initialValue":[
],
"in":{
"$setUnion":{
"$concatArrays":[
"$$this",
"$$value"
]
}
}
}
}
}
}
]
但是,我建议您检查模式设计并删除动态字段的名称
“LastReaders”字段可能如下所示:
{
"lastReadings":[
{
"parameter":"7-Temperature",
"value":{
"_t":"NumberReading",
"timestamp":"2017-02-13T12:51:50.000+0000",
"unit":"C",
"typeCode":7,
"name":"Temperature",
"numberValue":11.271406207825713
}
},
{
"parameter":"30-DISCONNECT",
"value":{
"_t":"NumberReading",
"internalTimestamp":"2017-06-02T19:16:33.050+0000",
"timestamp":"2017-06-02T19:16:27.147+0000",
"unit":"",
"typeCode":30,
"name":"DISCONNECT",
"numberValue":1
}
}
]
}
使用这种模式,您可以使用.disctinct
方法和点表示法检索不同的值
db.collection.distinct("lastReadings.parameter")