MongoDb - 如何查找数组中element1的位置小于element2位置的文档?

时间:2017-08-29 21:15:59

标签: arrays mongodb

因此,如果我有一个基本的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 之前。

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<>());