在 MongoDB 中,如何实现类似下面的 SQL 语句?
select count(*),t1.a,t1.b
from t1, t2
where (t1.id = t2.t1_id)
and (t2.t1_id in (select id
from t1
order by id desc
limit 10))
group by 2,3
order by 1 desc
我想出了除了嵌套选择之外的所有事情。
我目前正在使用"$in"
嵌套选择的每个值在循环中运行外部选择。Java代码如下:
BasicDBList t1List = new BasicDBList();
DBObject inClause = new BasicDBObject("$in", t1List);
DBObject t2Query = new BasicDBObject("t1s", inClause);
DBObject nextt2;
for (int query = 0; query < 10; query++)
{
System.out.printf("Running query %d - ", query);
DBCursor top_ten_t1s = t1Coll.find().sort(new BasicDBObject("v", -1)).limit(10);
while (top_ten_t1s.hasNext())
{
nextt2 = top_ten_t1s.next();
t1List.clear();
t1List.add(new Long(nextt2.get("_id").toString()));
int theCount = t2Coll.find(t2Query).count();
}
}