适用于您的用例的 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
运算符在功能上是等效的,但是使用该运算符会带来一些问题局限性 https://docs.mongodb.com/manual/reference/operator/query/where/#considerations:
$where
评估 JavaScript 并且无法利用索引。因此,当您使用标准 MongoDB 运算符(例如,$gt
, $in
).
一般来说,您应该使用$where
仅当您无法使用其他运算符表达查询时。如果你必须使用$where
,尝试包含至少一个其他标准查询运算符来过滤结果集。使用$where
仅需要收集扫描。