Slicing Arrays in MongoDB Documents


The "slice" operation in MongoDB allows you to extract a specified number of elements from an array field within a document. This operation is particularly useful when you want to retrieve a subset of elements from an array without fetching the entire array. It can be handy for pagination or when you need to work with a specific range of elements within an array, such as the most recent items or a specific page of results.

Example

[
  {
    "Name":"Vinoth",
    "Age":23,
    "Gender":"Male",
    "Skill":["c","c++","java","python"],
    "University":"Anna University "
  },
   {
    "Name":"Deppak",
    "Age":25,
    "Gender":"Male",
    "Skill":["javaScript","MYSQL","bootstrap-5","mongo DB"],
    "University":"Periyar University "
  }, {
    "Name":"Sara",
    "Age":28,
    "Gender":"Female",
    "Skill":["SQL","express js","react js","node js"],
    "University":"Annamalai University "
  }
]

SYNTAX

db.collectionName.find({"condition"}{"feildName":{$slice:index value}})

The code you provided is a MongoDB query that searches for documents in a collection named "data" where the "Name" field is equal to "Sara." It then projects the "Skill" field using the $slice operator to retrieve only the first 2 elements from the "Skill" array within each matching document. Here's a breakdown of the code

db.data.find({"Name":"Sara"},{"Skill":{$slice:2}})
  • db.data.find({"Name":"Sara"}): This part of the code performs a find operation in the "data" collection. It searches for documents that meet the specified criteria, where the "Name" field is equal to "Sara."
  • {"Skill": {$slice: 2}}: After the find operation, the projection part of the query specifies which fields to include in the result. In this case, it's specifying that only the "Skill" field should be included. Additionally, the $slice operator is applied to the "Skill" field, indicating that only the first 2 elements of the "Skill" array should be included in the result.

Output

Slice

So, when you run this code against your MongoDB database, it will return all documents where "Name" is "Sara," and for each of those documents, it will include only the first 2 elements of the "Skill" array in the result. The result will be a list of documents with "Name" equal to "Sara," and each document will have a "Skill" array containing at most 2 elements.

Descending Order in Slicing

Filter or remove First two index value

db.collectionName.find({"condition"}{"feildName":{$slice:-index value}})

The below code you provided is a MongoDB query that searches for documents in a collection named "data" where the "Name" field is equal to "Vinoth." It then projects the "Skill" field using the $slice operator with a negative value of -2.

db.data.find({"Name":"Vinoth"},{"Skill":{$slice:-2}})
  • db.data.find({"Name":"Vinoth"}): This part of the code performs a find operation in the "data" collection. It searches for documents that meet the specified criteria, where the "Name" field is equal to "Vinoth."
  • {"Skill": {$slice: -2}}: After the find operation, the projection part of the query specifies which fields to include in the result. In this case, it's specifying that only the "Skill" field should be included. The $slice operator is applied to the "Skill" field with a negative value of -2.

When you use a negative value with $slice, it indicates that you want to include the last N elements of the array, where N is the absolute value of the negative number. In this case, it includes the last 2 elements of the "Skill" array.

So, when you run this code against your MongoDB database, it will return all documents where "Name" is "Vinoth," and for each of those documents, it will include only the last 2 elements of the "Skill" array in the result.

Output

Slice

Parameter given in slice

In MongoDB, the $slice operator is used to project a specified number of elements from an array field within a document. The $slice operator takes one or two arguments:

db.collectionName.find({"condition"}{"feildName":{$slice:[starting index value,last index value]}})

Number of Elements: If you provide a single argument, it represents the number of elements you want to project from the beginning of the array.

Skip and Limit: If you provide two arguments, they represent the number of elements to skip and the number of elements to project, respectively. The first argument specifies the number of elements to skip from the beginning of the array, and the second argument specifies the number of elements to project.

db.data.find({"Name":"Sara"},{"Skill":{$slice:[1,2]}})

Output

Slice

Using Dollar Sign

The dollar sign ($) is used to indicate that MongoDB should project the specific matching element from the array.

Example

db.std.find(
    {"languages" : "Tamil"}, 
    {"languages.$" :1}
)

The MongoDB query you provided searches for documents in the "std" collection where the "languages" array contains the element "Tamil." It then projects the "languages" array element that matched the query using "languages.$": 1.

  • db.std.find(...): This part of the code performs a find operation in the "std" collection.
  • {"languages": "Tamil"}: This is the query criteria. It specifies that the documents to be retrieved must have an array field named "languages" that contains the element "Tamil."
  • {"languages.$": 1}: This is the projection part of the query. It specifies that only the "languages" array element that matched the query (in this case, "Tamil") should be included in the result. The dollar sign ($) is used to indicate that MongoDB should project the specific matching element from the array.

So, when you run this code against your MongoDB database, it will return all documents in the "std" collection where the "languages" array contains the element "Tamil," and for each of those documents, it will include only the "languages" array element that matched the query in the result.

Using ALL in array

Syntax

db.collectionName.find({"feildName":{$all:["index value" , "index value"]}})
[
  {
    "Name":"Sachin",
    "Language":["Tamil","English"],
    "Age":25,
    "Gender":"Male"
  },
  {
    "Name":"Virat",
    "Language":["Hindi","English"],
    "Age":34,
    "Gender":"Male"
  },
  {
    "Name":"Gill",
    "Language":["Hindi","Tamil"],
    "Age":29,
    "Gender":"Male"
  },
  {
    "Name":"Guna",
    "Language":["Tamil","English"],
    "Age":30,
    "Gender":"Male"
  },
  {
    "Name":"Mandhana",
    "Language":["Tamil","English"],
    "Age":25,
    "Gender":"Female"
  }
]
db.std.find(
    {"languages":{ 
        "$all" :[ "English", "Tamil"]
    }}
)

Output

all

The MongoDB query you provided searches for documents in the "std" collection where the "languages" array contains both "English" and "Tamil."

  • db.std.find(...): This part of the code performs a find operation in the "std" collection.
  • {"languages": { "$all": ["English", "Tamil"] }}: This is the query criteria. It specifies that the documents to be retrieved must have an array field named "languages" that contains all the elements listed in the $all operator. In this case, it's looking for documents where the "languages" array contains both "English" and "Tamil."

The $all operator is used to match documents where the specified array field contains all the elements provided in the array (["English", "Tamil"] in this case). It ensures that the document must contain both "English" and "Tamil" within its "languages" array for it to be considered a match.

So, when you run this code against your MongoDB database, it will return all documents in the "std" collection where the "languages" array contains both "English" and "Tamil."

Finding an Array by an Element

To find documents in MongoDB where an array contains a specific element

The MongoDB query syntax you provided uses the $and operator to combine multiple conditions in a query. Here's an explanation of the syntax:

db.collectionName.find({
  $and: [
    {"fieldName1": "condition1"},
    {"fieldName2": "condition2"}
  ]
})
  • db.collectionName.find(...): This part of the code performs a find operation in the specified collection (collectionName).
  • $and: The $and operator is used to specify that all the conditions inside it must be true for a document to be considered a match. In this case, it's used to combine two conditions.
  • {"fieldName1": "condition1"}: This is the first condition. It specifies that you want to find documents where the field named "fieldName1" matches the specified condition ("condition1").
  • {"fieldName2": "condition2"}: This is the second condition. It specifies that you want to find documents where the field named "fieldName2" matches the specified condition ("condition2").

Example

[
  {
    "Name":"Sam",
    "hobbies":["Painting","Reading","Writing"],
    "Age":45
  },
  {
    "Name":"Somu",
    "hobbies":["Walking","Reading","Writing"],
    "Age":45
  },
  {
    "Name":"Raju",
    "hobbies":["Painting","Reading","Cricket"],
    "Age":45
  }
 ]


db.std.find({
    $and:[
        {"hobbies" : "Painting"},
        {"hobbies" : "Reading"}
    ]
})

The MongoDB query you provided searches for documents in the "std" collection where the "hobbies" array contains both "Painting" and "Reading."

  1. db.std.find(...): This part of the code performs a find operation in the "std" collection.
  2. $and: The $and operator is used to specify that all the conditions inside it must be true for a document to be considered a match. In this case, it's used to combine two conditions.
  3. {"hobbies": "Painting"}: This is the first condition. It specifies that you want to find documents where the "hobbies" array contains the element "Painting."
  4. {"hobbies": "Reading"}: This is the second condition. It specifies that you want to find documents where the "hobbies" array contains the element "Reading."

The query effectively looks for documents where both conditions within the $and operator are satisfied. In this case, it's searching for documents where the "hobbies" array contains both "Painting" and "Reading."

Output

dollar and