因此,如果我有一个基本的mongo doc,其数组如:
{
myId: 1
nodes: [
{nodeId: 1},
{nodeId: 2},
{nodeId: 3}
]
}
或
{
myId: 1
nodes: [
{nodeId: 2},
{nodeId: 3},
{nodeId: 1}
]
}
我想查询以查找数组中 nodeId:2 的位置小于 nodeId:1 的所有文档。因此,对于上面的示例,我只想撤回第二个文档,因为 nodeId:2 出现在 nodeId:1 之前。
答案 0 :(得分:2)
您可以将$indexofArray
与$redact
结合使用。
$lt
比较索引和$$KEEP
当文档满足条件时,$$PRUNE
删除文档。
像
这样的东西db.collection_name.aggregate({
"$redact": {
"$cond": [
{
"$lt": [
{
"$indexOfArray": [
"$nodes.nodeId",
2
]
},
{
"$indexOfArray": [
"$nodes.nodeId",
1
]
}
]
},
"$$KEEP",
"$$PRUNE"
]
}
})
Mongo DB Java驱动程序代码:
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("db_name");
MongoCollection<Document> mongoCollection = database.getCollection("collection_name");
Document query = Document.parse("{\n" +
" \"$redact\": {\n" +
" \"$cond\": [\n" +
" {\n" +
" \"$lt\": [\n" +
" {\n" +
" \"$indexOfArray\": [\n" +
" \"$nodes.nodeId\",\n" +
" 2\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"$indexOfArray\": [\n" +
" \"$nodes.nodeId\",\n" +
" 1\n" +
" ]\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"$$KEEP\",\n" +
" \"$$PRUNE\"\n" +
" ]\n" +
" }\n" +
"}");
List<Document> documents = mongoCollection.aggregate(Arrays.asList(query)).into(new ArrayList<>());