JIYIK CN >

Current Location:Home > Learning > DATABASE > MongoDB >

Querying documents with array size greater than 1 in MongoDB

Author:JIYIK Last Updated:2025/04/27 Views:

When working with projects where you need to validate the size of an array or find elements whose size is greater or less than a certain length, you might use MongoDB operators such as $size, $where, $exists, etc.

The methods discussed below can help you solve the array length or array size problem.


Sample Data

Assume we have the following data. We will use this sample data to query documents with a specific array size in MongoDB.

db.inventory.insertMany([

{ item: "journal", qty: 25, tags: ["blank", "reds"], book: { author:`xyz`, price:50, location:[`india`, `USA`, `nepal`]} },

{ item: "notebook", qty: 50, tags: ["reds", "blank"], book: { author:`xyz`, price:50, location:[`india`, `usa`]} },

{ item: "paper", qty: 100, tags: ["reds", "blank", "plain"], book: { author:`xyz`, price:50, location:[]}},
{ item: "planner", qty: 75, tags: ["blank", "reds"], book: { author:`xyz`, price:50, location:[`india`]} },

{ item: "postcard", qty: 45, tags: ["blue"], book:{} }
]);

Using the $size operator in MongoDB to query documents with an array size greater than 1

The Array Operators class in MongoDB contains a number of operators for retrieving documents that reference arrays; $size is one of them. The $size operator is used to retrieve documents that contain an array field of a specific size.

It works only with arrays and accepts numeric values ​​as arguments.

Following are the main functions of the $size operator:

  1. It first compares the array field to the size given by the user and then continues.
  2. It retrieves documents that contain the fields that satisfy the previous steps.

grammar:

{array-field: {$size: <length-of-array>}}

In this case, array-field is the name of the desired field in the document, and array-length is any number matching length.

$sizeSome examples are shared below to understand how to use the operator in MongoDB .

db.inventory.find({tags:{$size:1}})

Output:

$size 1

db.inventory.find({books.location:{$size:1}}

Output:

$size 2


Using the $where operator in MongoDB to query documents with an array size greater than 1

To provide a string containing a JavaScript expression or a complete JavaScript function to the query system, use the $where operator. It allows greater flexibility, but it requires the database to execute the JavaScript expression or function for each document in the collection.

Use this or obj to refer to a record in a JavaScript expression or function.

grammar:

{ $where: <string|JavaScript Code> }

Given below is an example to illustrate $wherehow the operator works.

db.inventory.find({tags:{$where:`this.tags.length == 1`}}

Output:

$where 1

db.inventory.find({tags:{$where:`this.tags.length >= 1`}}

You can't $wherecheck this with the help of

The query operator is used only on top-level documents $where. It will not operate on nested pages.


Using dot notation to query documents with an array size greater than 1 in MongoDB

To access array elements and fields of embedded documents, MongoDB uses dot notation.

Accessing array elements

To specify or access an array element by its zero-based index position, concatenate the array name with a dot (.) and the zero-based index position, and then enclose it in quotation marks.

grammar:

"<array>.<index>"

For example, consider the following fields in a document.

{
   ...
   contribs: [ "Turing machine", "Turing test", "Turingery" ],
   ...
}

Use dot notation "contribs.2" to identify the third member in the contribs.2 array.

db.inventory.find({tags.0:{$exists:true`}}

It will look for elements with at least one tag // array with a zero-based index.
db.invantory.find({book.location.1: {$exists:true}}
// It looks for all components in whose book. There are at least two elements to a place.

Using $expr (3.6+) in MongoDB to query documents with an array size greater than 1

grammar:

{ $expr: { <expression> } }
db.invantory.find({
    $expr: {
        $gt: [{ $size: { $ifNull: ["$tags", []] } }, 0]
    }
})
db.invantory.find({
    $expr: {
        $gt: [{ $size: { $ifNull: ["$book.location", []] } }, 1]
    }
})
// $ifNull: ["$book.location", []] this is used to avoid any error if book.location is null

Querying documents with array size greater than 1 using aggregate $facet operator in MongoDB

This operator processes a large number of aggregations on the same set of input documents in a single stage. Each pipeline has its fields in the output document, where the results are saved as an array of documents.

The $facet stage supports the creation of faceted aggregations that characterize data across multiple dimensions or facets within a single aggregation stage. Faceted aggregations provide multiple filters and classifications to aid in data exploration and analysis.

For example, retailers often use facets to create filters to reduce search results based on product price, manufacturer, size, etc.

The input documents are sent to the $facet step only once. $facet allows to do numerous aggregations on the same set of input documents without retrieving them multiple times.

grammar:

{ $facet:
   {
      <outputField1>: [ <stage1>, <stage2>, ... ],
      <outputField2>: [ <stage1>, <stage2>, ... ],
      ...

   }
}

Enter the name of the output field for each pipeline.

Each sub-pipeline in $facet receives the same set of input documents. These sub-pipelines are independent of each other and the document arrays produced by each are stored in different fields of the output documents.

The output of one sub-pipeline cannot be used as the input of another sub-pipeline in the same $facet stage. Add additional stages after $facet and indicate the field name outputField> of the desired sub-pipeline output when further aggregation is needed.

Index usage in $facet stage

The $facet stage and its sub-pipelines cannot use indexes, even if its sub-pipelines use $match or if $facet is the initial step in the pipeline. During execution, the $facet stage always performs a COLLSCAN.

Consider an online store whose inventory is stored in the following collection of artworks:

{ "_id" : 1, "title" : "The Pillars of Society", "artists" : "Grosz", "year" : 1926,
  "price" : NumberDecimal("199.99"),
  "tags" : [ "painting", "satire", "Expressionism", "caricature" ] }
{ "_id" : 2, "title" : "Melancholy III", "artists" : "Munch", "year" : 1902,
  "price" : NumberDecimal("280.00"),
  "tags" : [ "woodcut", "Expressionism" ] }
{ "_id" : 3, "title" : "Dancer", "artists" : "Miro", "year" : 1925,
  "price" : NumberDecimal("76.04"),
  "tags" : [ "oil", "Surrealism", "painting" ] }
{ "_id" : 4, "title" : "The Great Wave off Kanagawa", "artists" : "Hokusai",
  "price" : NumberDecimal("167.30"),
  "tags" : [ "woodblock", "ukiyo-e" ] }
{ "_id" : 5, "title" : "The Persistence of Memory", "artist" : "Dali", "year" : 1931,
  "price" : NumberDecimal("483.00"),
  "tags" : [ "Surrealism", "painting", "oil" ] }
{ "_id" : 6, "title" : "Composition VII", "artist" : "Kandinsky", "year" : 1913,
  "price" : NumberDecimal("385.00"),
  "tags" : [ "oil", "painting", "abstract" ] }
{ "_id" : 7, "title" : "The Scream", "artist" : "Munch", "year" : 1893,
  "tags" : [ "Expressionism", "painting", "oil" ] }
{ "_id" : 8, "title" : "Blue Flower", "artist" : "O`Keefe", "year" : 1918,
  "price" : NumberDecimal("118.42"),
  "tags" : [ "abstract", "painting" ] }

The following process leverages MongoDB's faceting capabilities to show consumers a store's inventory organized by tag, price, and year of production. This $facet stage contains three sub-pipelines that perform this multifaceted aggregation using $sortByCount, $bucket, or $bucketAuto.

The input documents from Artwork are retrieved from the database only once at the beginning of the operation.

example:

db.artwork.aggregate( [
  {
    $facet: {
      "categorizedByTags": [
        { $unwind: "$tags" },
        { $sortByCount: "$tags" }
      ],
      "categorizedByPrice": [
        // Filter out documents without a price e.g., _id: 7
        { $match: { price: { $exists: 1 } } },
        {
          $bucket: {
            groupBy: "$price",
            boundaries: [  0, 150, 200, 300, 400 ],
            default: "Other",
            output: {
              "count": { $sum: 1 },
              "titles": { $push: "$title" }
            }
          }
        }
      ],
      "categorizedByYears(Auto)": [
        {
          $bucketAuto: {
            groupBy: "$year",
            buckets: 4
          }
        }
      ]
    }
  }
])

Output:

$facet 1

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

$unset operator in MongoDB

Publish Date:2025/04/27 Views:77 Category:MongoDB

This article will discuss how the $unset operator works in MongoDB. Additionally, we will demonstrate the use of this operator to remove a field from all documents in a MongoDB collection. $unset operator in MongoDB $unset is an operator us

Compass Filters in MongoDB

Publish Date:2025/04/27 Views:132 Category:MongoDB

This short article will cover the various ways to use Compass filters in MongoDB . Compass Filters in MongoDB MongoDB has a GUI called Compass . It is also known as MongoDB GUI. Users can use MongoDB to inspect the contents of their stored

Sorting by timestamp in MongoDB

Publish Date:2025/04/27 Views:54 Category:MongoDB

This article will introduce various methods of sorting timestamps in MongoDB. Sorting by timestamp in MongoDB sort() The method will sort documents in MongoDB. The method accepts a document containing a list of fields and the order in which

Deleting a user from a database in MongoDB

Publish Date:2025/04/27 Views:50 Category:MongoDB

This article will explain how to delete a user from a MongoDB database. In addition, we will see an example to make the topic easier to understand. Deleting a User from a MongoDB Database Sometimes we need to remove a particular user from t

Deleting items by ID in MongoDB

Publish Date:2025/04/27 Views:158 Category:MongoDB

Sometimes we need to delete data from a database based on specified criteria. Unlike other SQL databases, MongoDB does not include SQL queries for this purpose. Instead, it uses commands. This article will discuss how to delete documents ba

Using ISODate for date queries in MongoDB

Publish Date:2025/04/27 Views:77 Category:MongoDB

This MongoDB tutorial article will explain Date() the methods. This article introduces different ways to query using dates. Date() Method in MongoDB Date() The method returns the date as a string or a Date object. In the MongoDB shell or mo

Return unique values in MongoDB

Publish Date:2025/04/27 Views:189 Category:MongoDB

In this article, we will address how to use the MongoDB distinct() method to return unique values. In addition, returning unique values ​​in arrays and fields is discussed. In MongoDB, sometimes you may want to present or return unique

$ne operator in MongoDB

Publish Date:2025/04/11 Views:84 Category:MongoDB

This article will discuss how the $ne operator works in MongoDB. In addition, we will list its differences from the $not operator. $ne operator in MongoDB $ne is an operator in MongoDB that stands for not equal to. This will compare the val

MongoDB $Set Operator

Publish Date:2025/04/11 Views:159 Category:MongoDB

With the help of this article, you will learn how to use $set the operator to partially update objects in MongoDB so that the new object overlaps/merges with the existing object. The $set operator replaces the value of a field with a given

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial