skip to Main Content

A have a collection Products in MongoDB:

{
  "name": "My Product 01",
  "description": "This is an excelent product", 
  "tags": [
    "AA",
    "BBBB",
    "C",
    "DDDDDDDDDDD"
  ]  
}

How can I find the single longest occurrence if an item in the whole collection? (if I had only this object, the longest occurrence would be "DDDDDDDDDDD" with 11 characters).

2

Answers


  1. $unwind to tags level. Use $strLenCP to compute the length. Use $setWindowFields to $rank the length. $match rank: 1 to select the one(s) with longest length.

    db.Products.aggregate([
      {
        "$unwind": "$tags"
      },
      {
        "$set": {
          "length": {
            "$strLenCP": "$tags"
          }
        }
      },
      {
        "$setWindowFields": {
          "partitionBy": null,
          "sortBy": {
            "length": -1
          },
          "output": {
            "rank": {
              $rank: {}
            }
          }
        }
      },
      {
        "$match": {
          rank: 1
        }
      }
    ])
    

    Mongo Playground

    Login or Signup to reply.
  2. db.Products.aggregate([
      // Unwind the tags array
      {
        $unwind: "$tags"
      },
      // Project each tag with its length
      {
        $project: {
          tag: "$tags",
          length: {
            $strLenCP: "$tags"
          }
        }
      },
      // Sort by length in descending order
      {
        $sort: {
          length: -1
        }
      },
      // Limit to the longest tag
      {
        $limit: 1
      },
      // Project only the tag field
      {
        $project: {
          _id: 0,
          tag: 1
        }
      }
    ])
    

    generates:

    [
      {
        "tag": "DDDDDDDDDDD"
      }
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search