Query for documents where array size is greater than 1

MongodbMongodb Query

Mongodb Problem Overview


I have a MongoDB collection with documents in the following format:

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

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

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

This correctly returns the documents with 2 elements in the name array. However, I can't do a $gt command to return all documents where the name field has an array size of greater than 2:

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

How can I select all documents with a name array of a size greater than one (preferably without having to modify the current data structure)?

Mongodb Solutions


Solution 1 - Mongodb

There's a more efficient way to do this in MongoDB 2.2+ now that you can use numeric array indexes (0 based) in query object keys.

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

You can support this query with an index that uses 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}}}
);

Solution 2 - Mongodb

Update:

For mongodb versions 2.2+ more efficient way to do this described by @JohnnyHK in another answer.


  1. Using $where

    db.accommodations.find( { $where: "this.name.length > 1" } );

But...

> Javascript executes more slowly than the native operators listed on > this page, but is very flexible. See the server-side processing page > for more information.

  1. Create extra field NamesArrayLength, update it with names array length and then use in queries:

    db.accommodations.find({"NamesArrayLength": {$gt: 1} });

It will be better solution, and will work much faster (you can create index on it).

Solution 3 - Mongodb

I believe this is the fastest query that answers your question, because it doesn't use an interpreted $where clause:

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

It means "all documents except those without a name (either non existant or empty array) or with just 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" ] }
>

Solution 4 - Mongodb

You can use aggregate, too:

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 transit document and use it to filter the size of the name

Solution 5 - Mongodb

You can use $expr ( 3.6 mongo version operator ) to use aggregation functions in regular query.

Compare query operators vs aggregation comparison operators.

db.accommodations.find({$expr:{$gt:[{$size:"$name"}, 1]}})

Solution 6 - Mongodb

Try to do something like this:

db.getCollection('collectionName').find({'ArrayName.1': {$exists: true}})

1 is number, if you want to fetch record greater than 50 then do ArrayName.50 Thanks.

Solution 7 - Mongodb

MongoDB 3.6 include $expr https://docs.mongodb.com/manual/reference/operator/query/expr/

You can use $expr in order to evaluate an expression inside a $match, or find.

{ $match: {
       	   $expr: {$gt: [{$size: "$yourArrayField"}, 0]}
       	 }
}

or find

collection.find({$expr: {$gte: [{$size: "$yourArrayField"}, 0]}});

Solution 8 - Mongodb

None of the above worked for me. This one did so I'm sharing it:

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

Solution 9 - Mongodb

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

Solution 10 - Mongodb

I found this solution, to find items with an array field greater than certain length

db.allusers.aggregate([
  {$match:{username:{$exists:true}}},
  {$project: { count: { $size:"$locations.lat" }}},
  {$match:{count:{$gt:20}}}
])

The first $match aggregate uses an argument thats true for all the documents. If blank, i would get

"errmsg" : "exception: The argument to $size must be an Array, but was of type: EOO"

Solution 11 - Mongodb

Although the above answers all work, What you originally tried to do was the correct way, however you just have the syntax backwards (switch "$size" and "$gt")..

Correct:

db.collection.find({items: {$gt: {$size: 1}}})

Incorrect:

db.collection.find({items: {$size: {$gt: 1}}})

Solution 12 - Mongodb

You can MongoDB aggregation to do the task:

db.collection.aggregate([
  {
    $addFields: {
      arrayLength: {$size: '$array'}
    },
  },
  {
    $match: {
      arrayLength: {$gt: 1}
    },
  },
])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionemsonView Question on Stackoverflow
Solution 1 - MongodbJohnnyHKView Answer on Stackoverflow
Solution 2 - MongodbAndrew OrsichView Answer on Stackoverflow
Solution 3 - MongodbTobiaView Answer on Stackoverflow
Solution 4 - Mongodbone_cent_thoughtView Answer on Stackoverflow
Solution 5 - Mongodbs7vrView Answer on Stackoverflow
Solution 6 - MongodbAman GoelView Answer on Stackoverflow
Solution 7 - MongodbDaniele TassoneView Answer on Stackoverflow
Solution 8 - MongodblesolorzanovView Answer on Stackoverflow
Solution 9 - MongodbYadvendarView Answer on Stackoverflow
Solution 10 - MongodbBarrardView Answer on Stackoverflow
Solution 11 - MongodbSteffan PerryView Answer on Stackoverflow
Solution 12 - MongodbNagabhushan BaddiView Answer on Stackoverflow