如何在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();
}
}
答案 0 :(得分:0)
您不能在MongoDB的一个查询中执行此操作。你需要首先将内部查询的结果读入内存(听起来你已经在做了):
var ids = t1.find().sort( { _id: -1 } ).limit(10);
并将此结果应用于外部查询。