我需要你的帮助来使用MongoDB聚合框架和java驱动程序.

我想从我Collection 的所有物品中获取200个最古老的视图.以下是我的mongo查询(它在控制台模式下的工作方式与我所希望的一样):

db.myCollection.aggregate(
    {$unwind : "$views"},
    {$match : {"views.isActive" : true}},
    {$sort : {"views.date" : 1}},
    {$limit : 200},
    {$project : {"_id" : 0, "url" : "$views.url", "date" : "$views.date"}}
)

此集合中的项目有一个或多个视图.

推荐答案

最终找到了解决方案,我得到了与原始请求相同的结果.

Mongo驱动程序3:

Aggregate doc

MongoCollection<Document> collection = database.getCollection("myCollection");

AggregateIterable<Document> output = collection.aggregate(Arrays.asList(
        new Document("$unwind", "$views"),
        new Document("$match", new Document("views.isActive", true)),
        new Document("$sort", new Document("views.date", 1)),
        new Document("$limit", 200),
        new Document("$project", new Document("_id", 0)
                    .append("url", "$views.url")
                    .append("date", "$views.date"))
        ));

// Print for demo
for (Document dbObject : output)
{
    System.out.println(dbObject);
}

You can make it more readable with static import :
import static com.mongodb.client.model.Aggregates.*;.
See koulini answer for complet example.

Mongo驱动程序2:

Aggregate doc

Iterable<DBObject> output = collection.aggregate(Arrays.asList(
        (DBObject) new BasicDBObject("$unwind", "$views"),
        (DBObject) new BasicDBObject("$match", new BasicDBObject("views.isActive", true)),
        (DBObject) new BasicDBObject("$sort", new BasicDBObject("views.date", 1)),
        (DBObject) new BasicDBObject("$limit", 200),
        (DBObject) new BasicDBObject("$project", new BasicDBObject("_id", 0)
                    .append("url", "$views.url")
                    .append("date", "$views.date"))
        )).results();
    
// Print for demo
for (DBObject dbObject : output)
{
    System.out.println(dbObject);
}

Query conversion logic : Query conversion logic Thank to this link

Mongodb相关问答推荐

如何从MongoDB集合中获取第一个和最后一个元素?

如何在MongoDB中查找和过滤嵌套数组

如何在MongoSH中的现有文档中插入字段

有没有一种方法可以找到一个文档并通过 Go 更改 mongodb 中的 id/value 来克隆它

如何使用 Golang 库获取 MongoDB 版本?

Spring Boot MongoDB 连接问题

Node.js 和 MongoDB,重用 DB 对象

如何更新 mongodb 文档以向数组添加新元素?

使用 nodejs/mongoose 部分更新子文档

Clojure 和 NoSQL 数据库

如何使用 c# 2.0 驱动程序将数据插入到 mongodb 集合中?

mongo - 如何查询嵌套的 json

MongoDb:如何将附加对象插入对象集合?

当前的 URL 字符串解析器已弃用

Mongodb 类型引用 node

MongoDB聚合将字符串数组连接到单个字符串

mongodb:upserting:仅在插入文档时设置值

mongoosefind()不返回结果

如何在 Mongoid 中引用嵌入的文档?

Pymongo/bson:将 python.cursor.Cursor 对象转换为可序列化/JSON 对象