我想对这样的数据进行MongoDB聚合查询:
收藏A
{
_id : 1,
Active : true,
hasQuery : false,
Running : false,
}
{
_id : 2,
Active : true,
hasQuery : true,
Running : false,
}
{
_id : 3,
Active : true,
hasQuery : false,
Running : true,
}
{
_id : 4,
Active : true,
hasQuery : true,
Running : true,
}
{
_id : 5,
Active : false,
hasQuery : false,
Running : false,
}
{
_id : 6,
Active : false,
hasQuery : false,
Running : true,
}
这个JSON数据可以由像这样的表格架构表示 表A
PrimaryKey | Active | hasQuery | Running
1 | true | false | false
2 | true | true | false
3 | true | false | true
4 | true | true | true
5 | false | false | false
6 | false | false | true
如果我在表格中应用以下查询:
select * from A where Exists(Select * from A where A.Running=true and A.hasQuery=true) and A.Running=false and A.hasQuery=false and A.Active=true
union
select * from A where not Exists(Select * from A where A.Running=true and A.hasQuery=true) and A.Running=false and A.Active=true
我得到了这些结果: 在MongoDB中:
{
_id : 1,
Active : true,
hasQuery : false,
Running : false,
}
{
_id : 2,
Active : true,
hasQuery : true,
Running : false,
}
{
_id : 5,
Active : false,
hasQuery : false,
Running : false,
}
SQL中的:
PrimaryKey | Active | hasQuery | Running
1 | true | false | false
2 | true | true | false
5 | false | false | false
如何使用mongoDB聚合做同样的事情?
答案 0 :(得分:0)
我设法使用该代码:
db.test.aggregate(
{
$project:
{
RunningActiveRecordHasQuery:
{
$cond: { if: { $and: [ "$Running", "$hasQuery", "$Active"] }, then: true, else: false }
}
}
}
,
{
$match: {
RunningActiveRecordHasQuery : true
}
},
function (err, results) {
if (!err ) {
console.log (results.result);
match={}
if (results.length>0) {
match.AnyNotRunningActiveRecordHavingNoQuery=true;
} else {
match.AnyActiveRecordNotRunning=true;
}
db.test.aggregate(
{
$project:
{
_id: 1,
Running : 1,
Active : 1,
hasQuery : 1,
AnyNotRunningActiveRecordHavingNoQuery:
{
$cond: { if: { $and: [ {$eq: [ "$Running", false ] }, {$eq : [ "$hasQuery", false]}, "$Active"] }, then: true, else: false }
},
AnyActiveRecordNotRunning:
{
$cond: { if: { $and: [ {$eq: [ "$Running", false ] }, "$Active"] }, then: true, else: false }
}
}
}
,
{
$match: match
},
function (err, docs) {
}
)
}
}
)
它用于汇总以使事情有效。