[英]MongoDB Aggregation SQL Union and SQL Exists like clause
我想對像這樣的數據進行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聚合如何做同樣的事情?
我設法用該代碼:
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) {
}
)
}
}
)
它用於聚合以使事情正常運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.