Mongo-graphql:查询两个整数字段的按两个字段排序的命令,如果两个字段都有值,则返回两行

时间:2019-08-24 13:40:43

标签: mongodb

我有一个具有entry_height,exit_height(可能为null)的文档。 高度是比特币(区块高度)。多个条目可以具有相同的entry_height或exit_height。 我想显示一个列表,其中存在entry_height行,并且如果填充exit_height,还要显示第二行。

我需要按两个字段的高度排序。 假设我有以下条目:

1) entry_height: 1, exit_height: 5, entry_data, exit_data, ...
2) entry_height: 2, exit_height: 3, entry_data, exit_data, ...
3) entry_height: 4, exit_height: null, entry_data, null

查询结果为:

1) height: 1, entry related data...
2) height: 2, entry related data...
3) height: 3, exit related data ...
4) height: 4, entry related data...
5) height: 5, exit related data...

应该设置哪些索引以及如何从数据库中读取数据?

谢谢。

更新:经过一番阅读,我认为entry_height和exit_height应该是一个唯一的数组字段,例如height:[1,5],[2,3],[4]。 这样,我将建立一个多键索引。但是我不确定如何知道一个值是来自第一个高度输入还是第二个。 关于查询,我认为唯一的选择是聚合框架。 你怎么说?

1 个答案:

答案 0 :(得分:1)

这似乎可以解决问题:

var r = [
         {_id:0, "entry_height":1, "exit_height":5, "entry_data":"entry_DAT1", "exit_data":"exit_DAT1"},
         {_id:1, "entry_height":2, "exit_height":3, "entry_data":"entry_DAT2", "exit_data":"exit_DAT2"},
         {_id:2, "entry_height":4, "entry_data":"entry_DAT3"}
         ];

db.foo.insert(r);

c = db.foo.aggregate([
// The Juice!  "Array-ify" the doc and assign height and payload to common field names (h and d):
{$project: {x:[ {h:"$entry_height",d:"$entry_data",t:"ENTRY"}, {h:"$exit_height",d:"$exit_data",t:"EXIT"} ] }}

// The unwind creates 2 docs (in this case) for each input item
,{$unwind: "$x"}

// Toss out those items with no exit height (like _id = 2 above):
,{$match: {"x.h": {$exists: true} }}

// Finally:  The sort you seek:
,{$sort: {"x.h":1}}
]);

{ "_id" : 0, "x" : { "h" : 1, "d" : "entry_DAT1", "t" : "ENTRY" } }
{ "_id" : 1, "x" : { "h" : 2, "d" : "entry_DAT2", "t" : "ENTRY" } }
{ "_id" : 1, "x" : { "h" : 3, "d" : "exit_DAT2", "t" : "EXIT" } }
{ "_id" : 2, "x" : { "h" : 4, "d" : "entry_DAT3", "t" : "ENTRY" } }
{ "_id" : 0, "x" : { "h" : 5, "d" : "exit_DAT1", "t" : "EXIT" } }

高度是按顺序排列的,您可以使用t字段来确定d字段是输入数据还是退出数据。如果您还有其他嗅探数据的方法,则可能不需要t字段。

关于索引,不确定要索引的内容以减少聚合管道顶部的查找空间。