Search code examples
arraysspringmongodbsizegt

retrieve all data by size of array in spring mongo template


Suppose I have these:

{id: 1, name: name1, tags: [{id: 1, name: tag1}]},
{id: 2, name: name2, tags: []},
{id: 3, name: name3, tags: [{id: 3, name: tag3}, {id:33, name: tag33}]},
{id: 4, name: name4}

Then execute a query and I want this:

{id: 1, name: name1, tags: [{id: 1, name: tag1}]},
{id: 3, name: name3, tags: [{id: 3, name: tag3}, {id:33, name: tag33}]}

Getting documents that have "tags" array and its size is larger than 0. But don't know how to create my criteria.

I tried this but throws an error saying that size() has to take an argument of int...

where(tags).size().gt(0)

Anyone knows the correct one?


Solution

  • '$size' operator doesn't accept the range parameters. You could use positional value existence to decide the size. as follows

    db.collection.find({
      "tags.0": {
        $exists: true
      }
    })
    

    In Spring, You could try as follows,

    mongoTemplate.find(Query.query(Criteria.where("tags.0").exists(true)));