Locke
Locke

Reputation: 544

MongoDb - How to find documents where position of element1 in array is less than position of element2?

So if I have a basic mongo doc with an array such as:

{
  myId: 1
  nodes: [
   {nodeId: 1},
   {nodeId: 2},
   {nodeId: 3}
  ]
}

or

{
  myId: 1
  nodes: [
   {nodeId: 2},
   {nodeId: 3},
   {nodeId: 1}
  ]
}

I want to have a query to find all documents where the position of nodeId: 2 in the array is less than nodeId: 1. So for the example above I only want to pull back the second document since nodeId: 2 appears before nodeId: 1.

Upvotes: 0

Views: 166

Answers (1)

s7vr
s7vr

Reputation: 75914

You can use $indexofArray in combination with $redact.

$lt to compare indexes and $$KEEP when document when condition is met else $$PRUNE to remove the document.

Something like

db.collection_name.aggregate({
  "$redact": {
    "$cond": [
      {
        "$lt": [
          {
            "$indexOfArray": [
              "$nodes.nodeId",
              2
            ]
          },
          {
            "$indexOfArray": [
              "$nodes.nodeId",
              1
            ]
          }
        ]
      },
      "$$KEEP",
      "$$PRUNE"
    ]
  }
})

Mongo DB Java Driver Code:

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

Upvotes: 2

Related Questions