【发布时间】:2018-03-15 18:21:08
【问题描述】:
我收到以下查询:
db.getCollection('Messages').aggregate(
{
$match :
{
"header.MessageType" : { $in: ["04"] },
}
},
{
$project:
{
_id: '$_id',
header: '$header',
content: '$content',
q0: { $arrayElemAt: [ "$content.Changes", 0 ] },
q1: { $arrayElemAt: [ "$content.Changes", 1 ] },
q2: { $arrayElemAt: [ "$content.Changes", 2 ] },
q3: { $arrayElemAt: [ "$content.Changes", 3 ] },
q4: { $arrayElemAt: [ "$content.Changes", 4 ] },
q5: { $arrayElemAt: [ "$content.Changes", 5 ] },
}
},
{
$match :
{
"q0":"1"
}
},
{
$sort : { "sequenceID" : -1, }
},
{
$limit : 1
}
);
这给了我以下结果:
/* 1 */
{
"_id" : ObjectId("57288ecb53f65928c4ba4995"),
"header" : {
"MessageType" : "04",
...
},
"content" : {
...
},
"q0" : "1",
"q1" : "0",
"q2" : "1",
"q3" : "0",
"q4" : "0",
"q5" : "0"
查询给了我最近的文档(根据 sequenceID),它的 'q0' 绝对等于 1(其他 qx 字段可能是 0 或 1)。 我想对 q1,q2,...,q5 做同样的事情。换句话说,我想要一个包含 6 条记录的结果,每条记录代表其 'qn' (n=0..5) 记录绝对为 '0' 的最新文档。
是否可以将以下部分重复 6 次(对于 $match 部分中的不同 qx 值)然后组合它们?
{
$match :
{
"q0":"1"
}
},
{
$sort : { "sequenceID" : -1, }
},
{
$limit : 1
}
或者有没有更好的解决方案?
--- 编辑(添加了一些示例 [和简化] 数据):
/* 1 */
{
"_id" : ObjectId("57288fa553f65928c4bf4b2b"),
"header" : {
"MessageType" : "04"
},
"content" : {
"Changes" : [
"0",
"1",
"1",
"1",
"1",
"0"
]
},
"sequenceID" : NumberLong(369851),
"messageDate" : 13950214
}
/* 2 */
{
"_id" : ObjectId("57288fa453f65928c4bf4863"),
"header" : {
"MessageType" : "04"
},
"content" : {
"Changes" : [
"0",
"0",
"1",
"0",
"0",
"0"
]
},
"sequenceID" : NumberLong(369139),
"messageDate" : 13950214
}
/* 3 */
{
"_id" : ObjectId("57288fa353f65928c4bf43c2"),
"header" : {
"MessageType" : "04"
},
"content" : {
"Changes" : [
"0",
"1",
"0",
"0",
"0",
"0"
]
},
"sequenceID" : NumberLong(367953),
"messageDate" : 13950214
}
每个文档都表示一个或多个(最多 6 个)修改。修改见 q0..q5 字段。作为输出,我需要的是每个 qx 字段的最新更改。文档的顺序可以由“sequenceID”字段确定。换句话说,如果我(逻辑上做一个)OR 结果中所有文档的 q0..q5,它应该是 ["1","1","1","1","1","1" ].
【问题讨论】:
-
您想要多个匹配语句?如果是,那么它是可能的。
-
很难猜测,因为没有输入文档示例 - 这可能会推动我在回答中提出的其他解决方案
-
@rummykhan 我需要的是多个匹配语句同时在管道的同一阶段运行。这可能吗?
-
@profesor79 我添加了一些示例数据,同时我正在检查您的答案。
-
@rummykhan 那么您能否解释一下您的解决方案作为答案?
标签: mongodb aggregation-framework