0

在 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();
    }
}
4

1 回答 1

0

您不能在 MongoDB 中的一个查询中执行此操作。您需要先将内部查询的结果读入内存(听起来您已经在这样做了):

var ids = t1.find().sort( { _id: -1 } ).limit(10);

并将此结果应用于外部查询。

于 2013-07-17T20:06:35.070 回答