您的用例的 MongoDB(v3.4 之前)shell 命令是:
db.collection.aggregate([
{
"$redact": {
"$cond": [
{ "$gt": [ "$pub-date", "$rel-date" ] },
"$$KEEP",
"$$PRUNE"
]
}
}
])
将这个命令翻译成Java你会得到:
MongoClient mongoClient = ...;
MongoCollection<Document> collection = mongoClient.getDatabase("...").getCollection("...");
List<Document> documents = collection.aggregate(Arrays.asList(
new Document("$redact", new Document("$cond",
Arrays.asList(new Document("$gt", Arrays.asList("$pub-date", "$rel-date")), "$$KEEP", "$$PRUNE"))
))).into(new ArrayList<>());
for (Document document : documents) {
System.out.println(document.toJson());
}
给定一个包含这些文档的集合...
{
"_id" : ObjectId("5acb40d27d63b61cb002bafe"),
"title" : "WingsOfFire",
"pub-date" : ISODate("2013-10-02T00:00:00.000Z"),
"rel-date" : ISODate("2013-11-02T00:00:00.000Z")
}
{
"_id" : ObjectId("5acb662756539a6734e64e4a"),
"title" : "WingsOfSmoke",
"pub-date" : ISODate("2013-11-02T00:00:00.000Z"),
"rel-date" : ISODate("2013-10-02T00:00:00.000Z")
}
.. 上面的 Java 代码将打印 ...
{ "_id" : { "$oid" : "5acb662756539a6734e64e4a" }, "title" : "WingsOfSmoke", "pub-date" : { "$date" : 1383350400000 }, "rel-date" : { "$date" : 1380672000000 } }
...因为此文档的 pub-date (2013-11-02T00:00:00.000Z) 在其 rel-date (2013-10-02T00:00:00.000Z) 之后。
注意:$where 运算符在功能上是等效的,但使用该运算符时会附带一些 limitations:
$where 评估 JavaScript 并且不能利用索引。因此,当您使用标准 MongoDB 运算符(例如,$gt、$in)表达查询时,查询性能会提高。
一般来说,只有当您无法使用其他运算符表达您的查询时,您才应该使用$where。如果您必须使用$where,请尝试至少包含一个其他标准查询运算符来过滤结果集。单独使用 $where 需要进行集合扫描。