Query documents with array size greater than 1

Keywords: MongoDB

I have a MongoDB set. The file format is as follows:

{
  "_id" : ObjectId("4e8ae86d08101908e1000001"),
  "name" : ["Name"],
  "zipcode" : ["2223"]
}
{
  "_id" : ObjectId("4e8ae86d08101908e1000002"),
  "name" : ["Another ", "Name"],
  "zipcode" : ["2224"]
}

I can now get documents that match a specific array size:

db.accommodations.find({ name : { $size : 2 }})

This correctly returns the document with 2 elements in the name array. However, I cannot execute the $gt command to return all documents with an array size greater than 2 for the name field:

db.accommodations.find({ name : { $size: { $gt : 1 } }})

How to select all documents whose name array size is larger than one (it is better not to modify the current data structure)?

#1 building

I believe this is the fastest query to answer your question because it does not use the $where clause of the explanation:

{$nor: [
    {name: {$exists: false}},
    {name: {$size: 0}},
    {name: {$size: 1}}
]}

It means "all documents except those without names (nonexistent or empty arrays) or with only one name.".

Test:

> db.test.save({})
> db.test.save({name: []})
> db.test.save({name: ['George']})
> db.test.save({name: ['George', 'Raymond']})
> db.test.save({name: ['George', 'Raymond', 'Richard']})
> db.test.save({name: ['George', 'Raymond', 'Richard', 'Martin']})
> db.test.find({$nor: [{name: {$exists: false}}, {name: {$size: 0}}, {name: {$size: 1}}]})
{ "_id" : ObjectId("511907e3fb13145a3d2e225b"), "name" : [ "George", "Raymond" ] }
{ "_id" : ObjectId("511907e3fb13145a3d2e225c"), "name" : [ "George", "Raymond", "Richard" ] }
{ "_id" : ObjectId("511907e3fb13145a3d2e225d"), "name" : [ "George", "Raymond", "Richard", "Martin" ] }
>

#2 building

Because you can use the numeric array index in the query object key, there is a more efficient method in MongoDB 2.2 +.

// Find all docs that have at least two name array elements.
db.accommodations.find({'name.1': {$exists: true}})

You can support this query by using the index of a partial filter expression (requires 3.2 +):

// index for at least two name array elements
db.accommodations.createIndex(
    {'name.1': 1},
    {partialFilterExpression: {'name.1': {$exists: true}}}
);

#3 building

None of the above is useful to me. This is because I want to share:

db.collection.find( {arrayName : {$exists:true}, $where:'this.arrayName.length>1'} )

#4 building

You can also use aggregation:

db.accommodations.aggregate(
[
     {$project: {_id:1, name:1, zipcode:1, 
                 size_of_name: {$size: "$name"}
                }
     },
     {$match: {"size_of_name": {$gt: 1}}}
])

//You add "size of name" to the shipping document and use it to filter the size of the name

#5 building

db.accommodations.find({"name":{"$exists":true, "$ne":[], "$not":{"$size":1}}})

Posted by kashmirekat on Sun, 05 Jan 2020 02:29:28 -0800