我使用java async driver for mongoDb而不是默认驱动程序
我有一个带有'collect'集合的db'test',每个文档都在下面给出的表格中,其中time是10位unix时间戳
{ "_id", "userId", "programId", "time" }
我想写一个等同于下面给出的sql查询的查询,其中input1是unix时间戳格式的当前时间,input2是userId作为输入
SELECT *
FROM collect
WHERE time >= input1 AND userId = input2
ORDER BY time DESC
LIMIT 30
我做了类似的事
collection = db.getCollection("ProgramBookings"); Long Datetimesatmp =
new Date().getTime() / 1000;
Aggregate.Builder builder = new Aggregate.Builder();
builder = (builder.match(where("time").
greaterThan(Datetimesatmp.toString()).and("userId") .equals(userId.toString())).sort(desc("time"))).limit(30);
Aggregate d1 = builder.build();
这里我的意思是只检索符合条件的列表'时间'。但我被困在这里谷歌搜索后找不到很多有用的链接。我提到this link来执行上面给出的代码。有没有一种简单的方法可以做到这一点。
编辑: 我想将值添加到List of ProgramTime对象,就像
public class ProgramTime {
private Integer userId;
private Integer programId;
private Long time;
}
答案 0 :(得分:1)
我不认为聚合框架是正确的选择。我会直接'找'。有一个Find
类和嵌套Find.Builder
类用于构造更复杂的查询。
import static com.allanbank.mongodb.builder.QueryBuilder.where;
import com.allanbank.mongodb.MongoClient;
import com.allanbank.mongodb.MongoCollection;
import com.allanbank.mongodb.MongoFactory;
import com.allanbank.mongodb.MongoIterator;
import com.allanbank.mongodb.bson.Document;
import com.allanbank.mongodb.builder.Find;
import com.allanbank.mongodb.builder.Sort;
public class StackOverFlow {
// SELECT * FROM collect
// WHERE time >= input1 AND userId = input2
// ORDER BY time DESC
// LIMIT 30
public static void query(long input1, String input2) {
MongoClient client = MongoFactory
.createClient("mongodb://localhost:27017/");
// SELECT * FROM collect -- Kinda...
MongoCollection collection = client.getDatabase("test").getCollection(
"collect");
Find.Builder builder = Find.builder();
// WHERE time >= input1 AND userId = input2
builder.query(where("time").greaterThan(input1).and("userId")
.equals(input2));
// ORDER BY time DESC
builder.sort(Sort.desc("time"));
// LIMIT 30
builder.limit(30);
try (MongoIterator<Document> iter = collection.find(builder)) {
for (Document doc : iter) {
System.out.println(doc);
}
}
}
}