Home > database >  MongoDB: How to query arrays in embedded document within several depth?
MongoDB: How to query arrays in embedded document within several depth?

Time:09-29

If this is the one questioned before, please let me know. But I couldn't get exact answer from official docs or stackoverflow.

My mongodb document looks like this.

{
    "_id": ObjectId("614e1b600146c86a7d5cb524"),
    "hash": "hash_1",
    "logs": [
        {
            "address": "address_1",
            "topics": [
                "AAA",
            ],
        },
        {
            "address": "address_2",
            "topics": [
                "CCC",
                "DDD",
            ],
        },
    ],
},

{
    "_id": ObjectId("614e1b470146c86a7d5cacd0"),
    "hash": "hash_2",
    "logs": [
        {
            "address": "address_3",
            "topics": [
                "EEE",
                "FFF"
            ],
        },
    ],
}

I only want to query documents that the first value of topics field of an element in logs field equals with certain value, say "CCC". So can be said like this.

results = []
logs.map((log) => log.topics[0] = "CCC" ? results.push(log))
return results

And I only want elements in logs field with that meet the condition above. Is that possible?

CodePudding user response:

  • $match match the condition to reduce document
  • $project filter array

data

{
    "_id": ObjectId("614e1b600146c86a7d5cb524"),
    "hash": "hash_1",
    "logs": [
      {
        "address": "address_1",
        "topics": [
          "AAA"
        ]
      },
      {
        "address": "address_2",
        "topics": [
          "CCC",
          "DDD"
        ]
      }
    ]
},
{
    "_id": ObjectId("614e1b470146c86a7d5cacd0"),
    "hash": "hash_2",
    "logs": [
      {
        "address": "address_3",
        "topics": [
          "EEE",
          "FFF"
        ]
      }
    ]
}

aggregate

db.collection.aggregate([
  {
    "$match": {
      "logs.topics.0": "CCC"
    }
  },
  {
    $project: {
      hash: 1,
      logs: {
        $filter: {
          input: "$logs",
          as: "log",
          cond: {
            $eq: [
              {
                $first: "$$log.topics"
              },
              "CCC"
            ]
          }
        }
      }
    }
  }
])

result

{
  "_id": ObjectId("614e1b600146c86a7d5cb524"),
  "hash": "hash_1",
  "logs": [
    {
      "address": "address_2",
      "topics": [
        "CCC",
        "DDD"
      ]
    }
  ]
}

mongoplayground

  • Related