Schlagwortarchiv für: MongoDB


MongoDB database plays an important role in data storing and manipulating. To organize data, we create groups to gather the same sort of data in one place. Grouping can be on different attributes, whether from the count variable or any other feature. This tutorial will explain the group creation according to different fields of documents.

For the implementation of the phenomenon of groups according to multiple fields, we need to have some data in the database. We will create a database first. This is done by declaring the name of the database with the keyword “use.” For this implementation, we are using a database “demo.”

Merienda you are done with the database creation, data will be inserted into the database. And for the data entry we used to create “collections,” these are the containers that play an important role in storing limitless data in them. At a time, we can create many collections in a single database. Here we will create a database with the name “info.”

>> Db.createCollection(‘info’)

The response of MongoDB will be, “ok”; it is the confirmation of the creation of the collection. The data in the collection is entered row by row. So we will insert data into the collection. As this data will be used further in examples to create groups according to different fields, so we have entered many rows. Each time a different id is assigned to each row.

>>  db.info.insertOne ({«Name» : «Savid»,
«Age» : 28,
«Gender» : «Male»,
«Country»: «United States of America»})

Similarly, all the data will be inserted. You can see all inserted data by using the find() command

>> db.info.find().pretty()

Example 1: Group by Multiple Fields/Attributes

When we have a large set of data in the database, but we want to take a view of a few of them, then for this purpose, $groups are found. In this example, we will create a group to see some particular attributes from the collection. The group creador relies on the aggregate operation. An aggregate operation is used, to sum up the data according to the common fields. The Dollar “$” sign denotes the variable. Now apply a query on the above info collection.

A group depending on id, will be created. And then, only the age and gender documents are selected to be displayed. Whereas the entire data, including the name and country, are removed. This is somehow a filter that is used to limit the display of data.

>> db.info.aggregate([ {$group: {_id: {age:«$Age»,  gender:«$Gender»} } } ])

You can see that we have grouped each row according to id by limiting the data to two attributes.

Example 2: Group Through Multiple Fields by Applying a Condition

This refers to the grouping of the documents according to a specific condition. A group will be created on two attributes, and after the group creation, we will add a count variable to count the occurrence of the value of a specific document. And also, we have added a sorting order.

First, let us display the documents in our collection “new.” We have created a collection and added data to it earlier by following the same steps described above. We will only display all the items in the collection through the find() function.

The query will contain the group part first. The group is created on id; university and level are the two basic attributes that we want to get displayed. The variable we use gets the value from the collection and then assigns it to the query variable. All the values and conditions are not written directly in the command.

After the group creation, the condition is applied; it is to count and calculate the sum according to the levels of each document. After that, this answer will be arranged in descending order. This is done through the sort() functions. This function contains only two parameters; for the ascending value, it is 1, and for descending, it is -1.

>> db.new.aggregate([  {$group:{ _id:{ «university»:«$university», «level»:«$level»  },         «levelCount»:{«$sum»:1} }},  {«$sort»:{«levelCount»:1}} ])

The descending order will show that the greater amount of the level will be displayed first, and then the smaller one is displayed following the level document.

Example 3: MongoDb BUCKET Group by Multiple Fields

As the name indicates that the groups are found according to the bucket. This is done by creating the bucket aggregation. Bucket aggregation is the process of categorizing the documents into groups. This group acts like buckets. Each document is divided depending on the specific expression.

To elaborate on this concept, we will take a look at a collection we have created, and now we will apply the commands to that. A “draw” collection is created that stores the basic information regarding a person. We have displayed all the 4 rows entered into the collection earlier.

On the above data, we will apply a command to create a bucket (group) having the year as an attribute to group the data. We have also created boundaries in which the year of born and death are mentioned. The conditions applied on this command include the count variable to count the number of occurrences. We have also used a concatenation method here to combine both the first and the second names as strings. And also, the year of birth will be displayed. The id depends on the year.

When we compute this query, the resultant value will show that two rows are grouped depending on the age boundaries we have created.

Conclusion

The MongoDB feature of grouping depending on more than a single field is elaborated in this article by demonstrating the working of the aggregate operation in group creation. Any group function is incomplete without the aggregate feature. The group feature is applied directly through the different fields to limit the exposure of entire data. The grouping via multiple fields is also accomplished by applying a particular condition. In the end, we have described the creation of a bucket group that contains more items like a bucket.



Source link


“Insert, update, locate, delete, and aggregate are all operations that may be performed on a Time Series collection, just as they are on a standard collection. Behind the curtain, the fundamental difference exists. When you insert data into MongoDB, it is converted to an optimal storage format. A Time Series is simpler and more query-efficient than a regular collection.

Time Series collections are treated as non-materialized writable views in MongoDB. The data is saved more efficiently, conserving disc space, and a time-based internal index is built automatically. Instead of snappy, the zstd algorithm is used by default to compress the data. The new compression has a higher ratio, requires less CPU power, and is particularly well suited for time series analysis with minor differences between documents.

It is possible to change the compression algorithm in the future, although this is not encouraged. When you insert a document, a Time Series collection is not built automatically like other collections. It must be created expressly.”

What is Time-Series in MongoDB in Ubuntu 20.04?

A Time Series database is a customized database that is built for storing data created from a constant stream of values coupled with a timestamp efficiently. The most common application is storing data from sensorial equipment that delivers data points at regular intervals, but they are now employed to serve a far broader range of applications.

The following are some examples of possible applications:

  • Data from the internet of things
  • Web services, apps, and infrastructure are all under constant surveillance.
  • Estimating sales
  • Financial Trends Understanding
  • Data from self-driving cars or other physical objects are being processed.

A Time-Series specialized database uses compression technologies to reduce the amount of space needed while simultaneously providing access channels to dig deeper into the data. This enhances data retrieval and aggregation performance when using time range filters. They are more cost-effective than utilizing a traditional relational database.

The values in a Time Series should usually not change merienda they’ve been recorded; hence they’re designated as INSERT only or immutable data points. The update action is extremely rare merienda the data has been saved.

 Guidelines for MongoDB Time Series Data Storage in Ubuntu 20.04

We have some guidelines for time-series data in MongoDB, which are outlined below.

  • Consider the data features and query patterns while tuning your data for appropriate metaField and timeField.
  • When possible, combine time series data and time-series collections.
  • Individual measurements or sets of measurements should be saved as one document and added in batches when utilizing a time series collection.
  • Customize our data granularity about the attribute values of our metaField, or the distinct pairings of our unique metaField, based on our data intake pace.

How to Use Time-Series MongoDB in Ubuntu 20.04

When working with time-series data, you typically need more than just storage; you also need fast read and write functionality as well as advanced query capabilities. MongoDB now handles time-series data natively, as of MongoDB 5.0. The following options should be specified when giving a time-series collection in MongoDB:

The createCollection() command can be used to start a new time series collection.

timeField: The timeField option must be used when creating a time series collection. The timeField denotes the description of the property in each document that contains the date. We should also consider the following alternatives:

metaField: The metaField specifies the name of the column in each document that contains metadata. The metaField acts as a label or tag that allows time-series collections to identify a time series’ source. This field should not, and should only, change over time.

Granularity: If a matching metaField is supplied, the granularity attribute specifies the temporal gap between documents. The standard granularity is “seconds,” indicating a high-frequency intake rate for each time series defined by the metaField. Granularity could be adjusted to “seconds,” “minutes,” or “hours,” and it can be changed at any moment to make it worse. However, because you can’t change the granularity from “minutes” to “seconds,” it’s best to start with finer granularity and work your way up to a harsher granularity.

expireAfterSeconds: Finally, if you intend to delete data after a specified period, we can include the expireAfterSeconds field specifies how many seconds should pass before documents expire and are automatically destroyed.

Insert Documents With Time Series in MongoDB

At the very least, each document added to the time series collection must define the timeField. The date is the timeField in the illustration document below. It’s worth noting that timeField can be termed whatever you want as long as it’s of the BSON type or a Date. Any of the techniques for inserting documents into other MongoDB collections can be used to add documents to a time series collection. For this, we have created a collection of “webVisitors” as follows:

A single measurement should be included in each document we insert. Use the following command to insert many documents at merienda:

Retrieving Time-Series Data in MongoDB in Ubuntu 20.04

Time series documents can be queried like the documents from other collections of MongoDB. For example, with the MongoDB Shell, we have used a findOne to look for a document in the webVisitors collection() as follows.

The preceding query shows the following results, as you can see:

Aggregation on Time-Series Data in MongoDB in Ubuntu 20.04

Here, we have used an aggregate pipeline such as to add more query functionality. The following example aggregation pipeline combines all documents by measurement data and then delivers the media of all the visitor’s measurements taken on that day of a website:

When we execute the aggregation pipeline on the collection websiteVisitors, the output generated the media of the visitor’s document from the collection “websiteVisitors” as follows:

Conclusion

There is a lot of time-series data, but maintaining and accessing it can be difficult. MongoDB gained native support for time-series, making working with time-series data considerably easier, faster, and less expensive. We have given a brief introduction with some guidelines for using time-series in MongoDB. We have some illustrations of time series which demonstrate how we can use time series in the MongoDB collection in some possible ways.



Source link


“Have you ever heard about the data duplication concept while working in databases? When a record, thing, person, or place has its exact copy, that copy is said to be the duplicate of the flamante. While working in traditional databases, we use the WHERE clause to find out the duplicates within the table records, i.e., SQL, PostgreSQL. On the other hand, MongoDB doesn’t allow you to use the WHERE clause to find out the duplicates inserted within the collections of a specific database.

It came up with the aggregate function to find out the duplicate values from the collection. Within this article today, we will be discussing the insertion of duplicate records within the Mongo DB collections and display them on the MongoDB shell using the aggregate command of collections. Let’s start with our today’s article by the use of apt update and upgrade instructions within the terminal shell of the Ubuntu 20.04 system. For that, you need to log in first and open the shell by the use of “Ctrl+Alt+T.” After that, you can try the shown-below instruction at your shell and add the password for the user to continue the update process.”

It might require your confirmation to continue this process. Tap “y” upon asking: “Do you want to continue?”. After that, hit the Enter key.

It may take more or less time to process according to the situation of your system.

After the complete update, you will get the shown-below last lines of processing.

After the successful system update and upgrade, we have to open the MongoDB shell to insert some collections and records within the database. So, we have been using the “mongo” query to do so, as displayed in the image. The shell has been prepared successfully.

While using the “db” instruction at the MongoDB shell, we have found that the “test” database is available for our use.

Therefore, we have been using the “test” database for further queries and creating collection within it. For that, try the “use” instruction followed by the name of a database, i.e., “test.”

To add records, we need a collection in the test database. Thus, we need to create a new collection. For that, we have to try out the “db” instruction along with the “createCollection()” function of MongoDB, followed by the name of a new collection within its parenthesis, i.e., Data. The query was successful, and the collection was created successfully as per the status “ok: 1”. Moreover MongoDB, we tend to utilize the find() function preceded by the collection name to display the records of a specific collection. Therefore, we have tried the “db” instruction followed by the collection name, i.e., Data, and the function find() to do so. The collection “Data” is empty right now. Thus, we need to add some records to the collection.

To insert the records within the Data collection of MongoDB, we need to try out the insert() function within the “db” instruction along with the data in the form of documents, i.e., list format. We have been using a total of 4 columns for the document data of collections, i.e., _id, title, age, and price. We have added a total of 5 records for all these 4 columns of Data collection.

The record was added successfully as per the output above shows the number of records 5 for the “nInserted” option. After this, we will be using the find() function with the “Data” collection to find and display all the records of this collection. We are not passing any arguments to the parenthesis of a find() function to not restrict the collection records. All the 5 records for Data collection have been presented in the Mongo DB shell.

As we have been dealing with the topic of finding the duplicates in the collections of MongoDB, we must have some duplicate records in the collections as well. Therefore, we have been inserting three more records within the Data collection to be used as duplicates of some of the already inserted records. We need to update the “_id” column only as the ID of any column must be unique in MongoDB as we used to do in traditional databases. The same insert function has been used so far with the “Data” collection name. All three records have been added.

Now, when you run the “db” instruction with the collection name “Data” followed by the find() function merienda again on the MongoDB shell, the total of 8 records will be displayed on your screen. We can see the duplicate values for columns other than “_id” in this collection data.

It’s time to try out the aggregate() method for the “Data” collection to list out the specific column values that are duplicated in it. You need to use the shown-below syntax of an aggregate command in MongoDB. The option “$group” is used to add all duplicate values of a specific column in one, while the option $match will be utilized to find out the groups having more than 1 document. On the other hand, the “$project” option will be used to specify the format of showing the duplicate records. The first field of the “$group” option will specify the column name in which we will be searching for duplicates. A total of 3 records have been found duplicated for the column “title” of a Data collection. After this, the same query was tried for the “age” column and got the 3 results again.

Conclusion

The explanation of duplicate records has been given in the introductory paragraph, and we have discussed the difference between finding out the duplicates from traditional databases and MongoDB. For this purpose, we have tried to give an illustration about making a new collection within MongoDB and inserting records within it. Moreover, we have discussed the use of the aggregate function to find out the specific column containing the duplicate value within the collections. This article has displayed the clear difference in finding out the duplicates for MongoDB as a comparison to any other database.



Source link


“While working in the MongoDB database, we tend to utilize the “find” function more often to display the data from the collections as a document. The find() function can be utilized in different ways possible. You can use it to display or restrict the display of the specific number of columns at your output by specifying the column names to 1 or 0, respectively. Along with that, we can also define the multiple conditions within the find() function of MongoDB to restrict the number of records for the collection. Within the SQL database, we try to specify the conditions within the WHERE clause. But, within MongoDB, we need to use other ways. Thus, we have decided to cover those methods in this guide. Let’s start with our new article now. Before diving into the implementation deep down, we have to log in from Ubuntu 20.04 system and open its terminal by the utilization of Ctrl+Alt+T. After opening the shell, it is high time to update our system before going further. These updates are necessary for the smooth implementation of our article. Thus, try the shown below instructions followed by the password of a current user to continue.”

Affirm this action by pressing “y” upon asked. Press Enter to continue. The processing will be displayed on your terminal screen. Within a few seconds, your system will get up to date with the latest versions.

After the update has been completed, we have to launch the MongoDB shell at our Ubuntu 20.04 shell. For this, use the “mongo” keyword command as we did below.

The terminal of MongoDB has been launched and is ready to use. Let’s display the list of available databases of MongoDB in which we want to work via the “show dbs” instruction at its shell area. It will show the total databases available. First, three of them are built-in and used to store configuration data. We will be using the user-defined “test” database in this tutorial. To use the “test” database, try out the “use” instruction with the database name “test.” Press the “Enter” key to execute this instruction.

To try out the multiple conditions within the find() function of MongoDB, we must have some collection in the “test” database and sufficient records within the collection. Right now, our database is empty. Thus, we need to create a new collection from scratch. We need to try out the “createCollection” function within the “db” instruction, followed by the name of a new collection to be created in the parenthesis. We have named the collection “Data.” The query was successful, and the collection was generated successfully as per the “ok: 1” status.

Now, we have a new and empty collection of “Data” within our database. We need to put some values as a MongoDB document in it. To insert the data within the MongoDB collection, we need to try out the db insertion with the insert() function preceded by the collection name. Thus, we have been using the same “db” instruction with our newly created collection name, i.e., Data and the insert() function taking values within it. We have been adding a different number of columns for each document record. The column names are: “_id,” “Name,” “City,” “Age,” “salary,” and “job.” Not every record contains all the columns, as we have mentioned. But, each record must contain the “_id,” “Name,” City,” and “Age” columns within it. A total of 15 records have been added with this insert() function command, as shown.

Before trying the conditions on the Data collection, we will be simply using the “find” function to fetch all its records at merienda on our screen. So, we have tried the find() function within the “db” command of our MongoDB. This command has been displaying all 15 records.

As we have mentioned before, we can restrict the number of columns to be displayed in our MongoDB shell by the use of options 1 and 0 with the column name. So, we will try that as well. We have been restricting the display of column “_id” at the MongoDB shell by setting the column value of “_id” to 0 within the find() function. It displayed all the columns except “_id.”

Let’s use the conditions in the find() function now. Let’s suppose you want to display the only records from the Data collection where the City is “Paris.” For this, you need to specify the “$or” variable, and within its [] brackets, specify the column name with the value “Paris” as we did in the command displayed below. A total of 2 document records have been found so far.

We can also specify the names of the columns to be displayed within the find() instruction as we have done it within the shown instruction so far. A total of 3 records have been found.

Let’s use more than 1 condition for the same column using the “$or” variable in the find() function. So, we have been searching for the records that contain the “job” column value as “Doctor,” “Engineer,” and “ShopKeeper.” We have also specified the columns to be shown. It displayed a total of 3 records.

Apart from column values, you can use the comparison operators as well. We have been using the less than “lt” operator in the find() function to display the records only where the ID is less than 6. It shows a total of 5 records.

Just like that, we have tried the greater than comparison operator for the “salary” column within the find function and got the 3 records in return.

Conclusion

This article is the best help to show you the use of the find() function with multiple conditions to display records of collection within MongoDB. We have tried to cover the most in our illustrations to make you understand how easy it is to do with the find() instruction. We have tried the column values and the comparison operators to limit the number of records or display the specific document records on the shell, i.e., less than, greater than operators.



Source link


MongoDB is an open-source database management system that allows its users to add downloads and connect them easily with the server. As the name implies, like other databases, it will store data and will allow users to manage it. For this purpose, it has several functions (i.e. updateMany()). UpdateMany() is the command line function that is used to modify documents in the collection of MongoDB depending on the query we used. Modification is always related to either replacing the existing data or adding a new field in the record. Our current topic refers to the updateMany() feature in MongoDB. Let us start with the implementation to see how this command is relatable to each scenario.

When you open the terminal, you are now supposed to write any command regarding MongoDB. If you are not sure on the database you are connected with, simply write ‘db’. This will bring the name of the database.

The database will be either the default or a user-defined db. If you have not created a database of your own, then most probably MongoDB will use the default database, ‘test’. But to use the database of your own, you are required to use a command of ‘use’ with the database name.

Hence, demo is the user-defined database. MongoDB terminal will respond to which the database is switched from the test to the demo database.

Collection creation

Merienda you are done with database connectivity and creatione, your concern will rely on data entry. Similar to other databases, MongoDB also offers containers to store data. These are COLLECTIONS. Let’s see how collections are formed by using the name ‘test’.

>> db.createCollection(‘test’)

The createcollection command with the db keyword is used to create a collection along with the name in parenthesis. Make sure that the collection is created in the same database you want to use in the future. Because while creating a collection, the database name is not specified.

The response of MongoDB is ‘ok’, which means the collection is created successfully without any exception. We had already added data to the collection. Three attributes are added and assigned with the values respectively. To see all data, use the find() command.

>> db.test.find().pretty()

This command will fetch all the records of the test collection.

You can observe that 4 rows are entered into the collection.

UpdateMany()

Sometimes, you have entered the wrong data, or you need to add more fields to the record. In other words, you need modification of data. So, it is done through the UPDATE command.

MongoDB provides a facility to update the existing documents. There are two types to update the documents.

  • db.collection.updateOne() – It updates a single attribute in a collection.
  • db.collection.updateMany() – It is used to update many attributes through a single command, in the collection.

Note: Both Update types are useful, but it is recommended by the developers to use UpdateManny() as it consumes less time and makes the code shorter.

As our topic under discussion is updateMany, so we will go with it by describing the syntax.

# db.collection_name.updateMany(FILTER, name OF the attribute/document , options)

Here db denotes the current database and collection_name is the collection on which you want to apply the update command. Mainly there are three arguments in the function of the updateMany parameter.

  • Filter: It acts the same as the find() method. It shows the selection criteria for the update.
  • Document: It contains the value you want to add in the row or the one that can be used for replacement.
  • Options: It is an optional value that can be removed.

As we have created a collection and added sample data to it already, let’s apply the updateMany command on the collection.

Example 1: Update an existing record

This example refers to the modification of an already existing value. For instance, the filter portion of the command will find the name attribute. When the match is found, the value of the age feature is replaced.

>> db.test.updateMany({name: «david»}, {$set:{age: 20}})

In response to the command, MongoDB will acknowledge the query as true and will show that one match was found in the whole record. Then, the concerned row is modified.

To see the record we will use the find () command

>> db.test.find().pretty()

As a result, you will notice that the age of David was 26 when the record was entered but on applying the updateMany() function, the age feature is replaced with 20.

Example 2: Add a new attribute to the existing record

Now we will update a single field in the record of more than one person. Previously, we have used a name that is a unique attribute. It specifies only a single person. To target more, we have selected a section attribute. This time we will not modify the existing record, but the new one will be added. The attribute is “team” with a value. This will be added only in those rows that have section A.

>> db.test.updateMany({SECTION: «A»}, {$set:{Team: «Fruit»}})

The command will return that 2 rows are modified after finding the match. On using the find() function, you will get:

Example 3: Modify all record

If you want to add a new field in each row, we do not use any attribute in the filter of the command but empty brackets are mentioned.

>> db.test.updateMany({}, { $set: {eligibility: «True»}})

So the new eligibility attribute will be added in all rows.

Conclusion

This discussion was to provide the use of the updateMany() command in the MongoDB database. We gave a brief introduction to the database, collections, and insertion of data because they are the prerequisites for applying the updateMany() command. The update command can be further used in two subfields; Updateone() and UpdateMany(). UpdateMany is used in detail by using some examples that assist in learning and understanding this concept.



Source link


Today’s article is specifically designed for GUI lovers. You might be ordinario with MongoDB as a DBMS, however, after going through this guide, you will be able to work with it very effectively using the GUI. Therefore, let us get started with the installation procedure of the MongoDB Compass (which is the GUI tool for MongoDB) on Ubuntu 22.04 system. Along with that, we will also be discussing its basic usage so that you can use this tool without any difficulty.

Installation of MongoDB Compass on Ubuntu 22.04:

For installing the GUI of MongoDB and MongoDB Compass on Ubuntu 22.04 system, you will have to perform the following steps:

Step # 1: Updating the System Index:

First, you need to update your system’s index with the command given below:

Step # 2: Downloading MongoDB Compass on Ubuntu 22.04:

Merienda your system’s index has been updated successfully, you need to download the “.deb” file of MongoDB Compass by running the following command or you can even download it from the official site of MongoDB manually.

$ wget https://downloads.mongodb.com/compass/mongodb-compass_1.15.1_amd64.deb

When this command will finish its execution, the output shown below will be presented to you:

Step # 3: Installing MongoDB Compass on Ubuntu 22.04:

Then, you can install MongoDB Compass on your Ubuntu 22.04 system with the help of the following command:

$ sudo dpkg –i mongodb-compass_1.15.1_amd64.deb

Upon a successful installation of the MongoDB Compass on Ubuntu 22.04, the output shown below will appear on the terminal:

Usage of MongoDB Compass on Ubuntu 22.04:

Before starting to use the MongoDB Compass, you need to ensure that the MongoDB server is running on your Ubuntu 22.04 system. Otherwise, you will not be able to connect to the MongoDB database. Eventually, you will not be able to work with the MongoDB Compass. You can run the MongoDB server by executing the “mongo” command in your system’s terminal. Merienda the MongoDB server starts running on your system, you can carry out the following steps:

Step # 1: Launching MongoDB Compass on Ubuntu 22.04:

You can launch the MongoDB Compass by looking for it in the Application Menu’s search bar of your Ubuntu 22.04 system and clicking on the relevant search result. The welcome interface of the MongoDB Compass tool is shown in the image below:

When you close the welcome message dialogue box, you will be presented with the Privacy Settings dialogue box as shown in the following image. From here, you need to click on the Start Using Compass button for proceeding further.

Step # 2: Connecting to the MongoDB Database in Ubuntu 22.04:

Now, you need to connect to the MongoDB database. For that, you will have to type in your Nave Host Address in the space provided and click on the Connect button as shown in the image below:

Step # 3: Creating a Database and a Collection in MongoDB Compass:

After connecting to the MongoDB database, you can create a database and a collection in MongoDB Compass very easily. You should click on the Databases tab for creating a new database.

Here, all the three default databases will be presented to you. You can create a new one by clicking on the Create database button.

Upon clicking this button, you will be asked to type in the name of your database as well as the name of the collection that you want to create inside this database (you can even create more collections inside the same database later). After providing the names of the database and the collection, you have to click on the Create Database button as shown below:

Step # 4: Inserting a Document in the Collection in MongoDB Compass:

Now, you will be able to see your newly created database within the list of MongoDB databases. For inserting a document inside the newly created collection in your MongoDB database, you first need to expand the database tab by clicking on the name of your particular database as highlighted in the following image:

From here, you need to click on the name of your specific collection as shown below:

Merienda you are inside your new collection, you need to click on the ADD DATA button and then select the Insert Document option.

After doing this, you will be presented with a sample document as shown in the following image:

You can remove this sample document and add your own as shown in the image below. In the same manner, you can even insert multiple documents at a time separated from each other by commas. You need to be careful about the syntax of the query. After inserting the document[s], you have to click on the Insert button.

Now, you will be able to see the inserted document[s] inside your collection as shown below:

Step # 5: Deleting the Document in the Collection in MongoDB Compass:

For deleting a document, you need to hover over it and then click on the remove icon as highlighted in the following image:

Then, you need to confirm its deletion by clicking on the DELETE button.

Step # 6: Deleting the Collection in MongoDB Compass:

Finally, click on the three dots located with its name and then select the Drop Collection option.

After that, you can provide the confirmation by clicking on the Drop Collection option highlighted in the image shown below:

Conclusion:

This guide was primarily written to deliver two functions: the installation of MongoDB Compass and the use of MongoDB Compass on Ubuntu 22.04. We first talked about the installation of this tool on Ubuntu 22.04 by explaining each. It is followed by the very basic usage of this tool. By following this tutorial, you will easily be able to use MongoDB Compass for creating a database and a collection, inserting documents inside a collection, deleting documents from a collection, and deleting a MongoDB collection.



Source link


“The date is returned as a string or as an object in MongoDB’s date queries. The current date is returned as a string by date query in the mongo console. MongoDB will output the current date as an object of a date, which will be wrapped in an encapsulation assist. The date can be specified as an ISODate string, which is then provided to MongoDB’s new date() method within the defined range. If you’ve ever attempted to save a JavaScript Date object to MongoDB, you’ll notice that MongoDB wraps your date in an odd function called ISODate().

ISODate() allows you to visually portray a date in MongoDB as a String while allowing you to use date queries and indexing. The programmer can analyze date objects quickly and visually by enclosing the ISO date String in a function rather than converting it from a Unix timestamp to a time String.

Today, we’ll explore how to create a MongoDB Date greater than a query to retrieve records based on a timestamp or a date range. Examples of MongoDB date queries will be shown, such as MongoDB date greater than time or date, and so on.

Greater than operator($gt) is among MongoDB’s comparison operators. The greater than $gt operator is then used to discover documents where the value of a field is greater than (>) the value set. Depending on your needs, you can utilize this operator in functions such as locating, updating, and so on.”

Syntax of a Date Greater Than Query

The information below demonstrates how to use this syntax in a collection of data in practice.

db.collection_name.find({
    field_name: {
        $gt: ISODate(«date»),
        $lt: ISODate(«date»)
    }
})

This query returns all entries in the collection with a field name that is greater than or equal to the date passed in the ISODate method but less than or equal to the date returned by the ISODate method. Here $gt denotes the “greater than” symbol, and $lt indicates the “less than” symbol. The preceding steps are simple to follow. There are a few minor changes between these directions, though.

How to Create a Date Greater Than Query MongoDB in Ubuntu 20.04

This section demonstrates how to create a MongoDB date greater than a query that returns records depending on a timestamp. MongoDB date greater than time or date is included in the examples of a date query in MongoDB.

To further understand the concept, let’s create a data collection by inserting the document. The query to create a collection comprising a record is as follows:

First, we have established a database as a “shop” inside the mongo shell. Then, we have given a name to our collection as “Mart” inside the create collection query. As our collection is created, we have used the following query for creating the collection’s document.

In the above figure, we have inserted three documents inside the collection “Mart” with the insertMany query. Instead of inserting a record one at a time, we may use this query to enter a record all at merienda within the specified collection. Then, in the end, the acknowledged statement inserted the ID’s for the documents that show the documents are successfully inserted in the collection “Mart.”

Now, use these documents of the collection against the date greater than the query in the MongoDB shell. Let’s execute this query in the example implemented below.

Example # 1: Find a Record Between Two Dates in MongoDB in Ubuntu 20.04

To find all documents with a field name between two dates, we ran the following query.

We have utilized the find function here, and within the function, we have called a field “date” from the collection “Mart.” We have done a greater than and less than operation on the date field by giving two different ISODate from the collection. From this query, we yield an ISODate greater than the date “2022-03-12T00:00:00Z” and lesser than the date “2022-03-12T00:00:00Z”.

The above query returns the results between the “greater than” ISODate and “less than” ISODate in the following MongoDB snap shell.

Example # 2: Find a Record Greater Than the Specific Date in MongoDB in Ubuntu 20.04

We are using the greater than operator on the specific date to find the date from the document. And from this, we will get a date greater than a specific date in the query. Let’s demonstrate the statement by executing the query in MongoDB.

We have a db.Mart.find query inside which we have specified the date field. The date field has given a “greater than” operator as $gt, and the $gt operator has been assigned with the ISODate “2022-02-12”. If the ISODate is greater than this date from the document, it only displays those documents.

The above query returns the two documents which have the ISODate date greater than the date given to the $gt operator.

Example # 3: Retrieve a Record Based on a Date in MongoDB in Ubuntu 20.04

We are retrieving the record from the collection, where the date field matches the ISODate given in the query. We have utilized the greater than equal to operator. Let’s consider the example of using MongoDB to give a query based on the current date.

In the above query, we have a date field inside the find function. The date is using the greater than equal to operator “$gte” and specified the $gte operator the ISODate with utilizing the new keyword. After that pretty method is used at the end of the query to display the results in an easier format.

The date returned by the above query is shown in the following snapshot.

Conclusion

This article is based upon a date greater than the query in MongoDB. We have begun with a brief introduction where the Date function and the $gt operator in MongoDB are briefly explained. Also, we have shown the syntax of a date greater than the query. This article clearly shows you using the Date() method. The $gt and the $gte queries are also described in detail with examples. The use of code snippets to explain well how to retrieve a query-dependent date is also demonstrated.



Source link


MongoDB filter aggregation was introduced in version 3.2. It is used to choose a subset of an array and provide the result based on criteria. The filter operator returns an array of entries that fit the provided criterion in the order they were found. When using the filter operator in MongoDB, we must provide the input, as and cond as arguments. Input and cond are required parameters, however “as” is optional. We must use the $ sign before the filter keyword when we use the filter operator in MongoDB.

Syntax of the Filter Query MongoDB in Ubuntu 20.04?

The $filter operator provides an array with just those elements in the flamante order that match the condition. Mentioned below is the syntax of $filter:

{ $filter: { input: <array_field>, as: <string>, cond: <expression> } }

  • filter: The $filter operator is used to provide a result that meets certain criteria. In MongoDB, we used the filter operator to filter the results based on the criterion we specified in the query.
  • input: This is an array resolution expression. We managed to pass the array field as an input parameter to filter the records. Before we use the input field parameter in the filter operator, we must use the $ sign.
  • as: It’s a filter operator argument that’s optional. This is the field’s name which was utilized as an element in the input array. This parameter is of the string type in the filter operator. Using the “as” keyword, this expression accesses each element in an input array.
  • cond: This option determines where the value from the generated array should be included. This parameter is of the expression type in the filter operator. The values from the given collection were filtered using expression. We can use numerous conditional operators to filter data from array elements.

How the Filter Query works in MongoDB in Ubuntu 20.04:

A MongoDB $filter operator is used to filter documents from an array based on a condition that we defined in our query. Based on the given condition, returns a subset of an array. Only those array entries that satisfy the requirements are returned. The elements are reassembled in the same arrangement as before.

Let’s look at some instances to help you understand what we are discussing. As we proceed through the article, we would like you to try the examples in the mongo shell. We start by creating a database collection that utilizes throughout the article.

Here, we have defined a collection of the database as “candidates” by using the MongoDB shell. For this collection, we have the id, name, and marks field defined. We have inserted seven documents at the same time by using the insertMany query.

The collection “candidates” is invoking the find function as in the above query. Then, the recorded document displays the field and its corresponding values. Note that in the field “marks”, the array is defined with some random values.

Example 1:Using the $filter operator in MongoDB in Ubuntu 20.04:

The $filter operator is used to filter the array members in the field “marks” from the given collection in the following example:

We have utilized the aggregate query on the collection of “candidates”. Inside this query, we have the $match operator which is used to filter the document by the id. We have assigned the id field a $in operator. The $in operator finds documents where the value of id equals any value in the provided array. Then, the $filter operator is passed the input argument and sets its value “$marks”. The “as” parameter is also used which returns the field name “marks”. Then, we have specified the cond parameter that uses the greater than operator on the field “$$marks”.

By following the above query, the result we got is shown in the figure with the new field name highmarks.

Example 2:Using the $filter operator for an empty array in MongoDB in Ubuntu 20.04:

When one of our collection documents has an empty array, the filter operator returns an empty array set, as can be seen here:

Within the $match we have specified the id that has the $in operator which returns id “7” from the collection as we have given “7” inside an array. Then, the $filter query has provided the collection field “marks” which returns an empty array because no value is stored inside the “marks” field of id “7”.

The result of the filter operator has an empty set of the document here.

Example 3: Using the $filter operator for the wrong type in MongoDB in Ubuntu 20.04:

If we try to use the $filter on a field that doesn’t have an array, we will get an error. The following is the demonstration of this statement.

We have given a field “name” from the document whose id is “5” inside the $filter operator. In the parameter cond of $filter, we have the $eq operator which takes the field “$name” and matches the string value defined to it.

When we run the above query, the error message shows that the type must be an array in the $filter operator as seen in the figure.

Example 4: Using the $filter operator with the $this variable in MongoDB in Ubuntu 20.04:

We used the “as” parameter to give the variable a name in the earlier cases. The as parameter is optional. If we set this field blank, the variable name will be “this” by default.

Here, we have specified the array in $in operator which selects the id fields from the documents of the given collection within the $match. Then, the $filter has the two-parameter, input and cond. The cond parameter has the greater than operator which retrieves the marks greater than 65. We haven’t used them as a parameter, instead we utilized the $$this field name.

Hence by using $$this to reference the field, we got the same results as from the “as”. The output is satisfied with the $match condition and the $filter condition seen in the picture.

Conclusion:

This is a MongoDB Filter guide. In this article, we have gone through the definition, syntax, and how filters function in MongoDB. Examples and code implementation are also provided. The array field’s elements are filtered using the MongoDB filter operator. To retrieve data from array elements, we have utilized several conditions such as $gt, $lt, $gte, and $lte.



Source link


Due to its fast responsiveness, advanced version, sustainability, and strong indexing capabilities, MongoDB is one of the most renowned NoSQL databases. In many cases, MongoDB queries that classify data by looking for precise matches, utilizing significantly larger and less than comparisons, or employing regular expressions will suffice. When it comes to screening against fields with rich textual data, however, these strategies fall short. This guide will help us to create a MongoDB text index and use it to search for documents employing common full-text search queries and criteria.

When we see material employing phrases or keywords, the best example is a Google search. With MongoDB full-text search, we can establish a text index on any column in a document using a string or arrays of strings.

Syntax of the full-text search in MongoDB in Ubuntu 20.04 ?

The syntax mentioned is as follows:

db.Collection_Name.find({$text: {$search: “string”}})

The find() function is used with the following parameters in the syntax above:

  • Collection_Name: refers to the name of the existing collection.
  • Find: performed to search using the find.
  • $text: used to do a collection search that satisfies our objectives.
  • $search: used to perform the search.
  • String: refers to a certain string that we want to look for in the collection, and we can use the search function to find exact words.

Working on the $text operator in MongoDB in Ubuntu 20.04:

Text lists are provided by MongoDB to assist text searches on string content. Any field with a string value or a range of string components can be included in text records. You should have a text record in your collection to do text search questions. Even a collection only has one topic search record. A list can span multiple fields.

How the full-text search performs in MongoDB in Ubuntu 20.04

Now, look at certain examples to better comprehend things. First, we have created a database with the name “myDemo”. Inside this database, we have defined a collection as “fruits”. Then, the insertMany query is used to insert the collection document as the screenshot is displaying the fields and values against these fields for the collection “fruits” document below.

The query “db.fruits.find()” results into the attributes and the entities of the collection “fruits” as follows. We have three documents recorded for the collection of “fruits”.

Now, let’s examine how we can perform a full-text search.

Example # 1: Creating text index in MongoDB in Ubuntu 20.04:

We have to establish a text index on a dataset before you can use MongoDB’s full-text search features. Indexes are unique data structures that isolate a limited piece of data from each text in a collection from the documents themselves. Let’s have a look at how to perform a full-text search.

A text index is built in the same way as a conventional index, instead of defining an ascending/descending order, it defines the text keyword.

Above, we have a query for a full-text search. We have used the createIndex() method to create a text index. We set the two fields “subject” and “content” to the index-type text.

By running the createIndex query on the MongoDB shell, the following output confirms the index creation:

Example # 2: Searches for a word or phrase from full-text in MongoDB in Ubuntu 20.04:

Looking up documents comprising one or more single words is perhaps the most widespread search challenge. Users probably expect the web browser to be adaptable to choosing where the particular search phrases should display. When employing text indexes, MongoDB approaches common search queries in the same way. With a few examples, this step explains how MongoDB processes search requests.

Here, we have a query “db.fruits.find()”. The query employs the $text operator, which informs MongoDB here that the query will make use of the text index we previously defined. Also, only one text index is allowed in each collection. Then, inside the $text operator we have another operator called $search which is used to search the value “sweet” from the given documents.

As you can see, we have only one document with the text content “sweet”. By running the above query, the entire details of the document having the text content “sweet” are displayed as follows:

Now, we are searching for two words by using the following query:

We have given the two-word “vitamin C” to the $search operator which is called inside the $text operator. When the query is ran, it shows the document record having the vitamin C listed in the text as follows:

Example # 3: Scoring and sorting the full-text search results in MongoDB in Ubuntu 20.04:

Each document receives a score from the text search that indicates how relevant it is to the search query. This score is used to categorize all of the records in a search result. A higher score means the contest is more meaningful.

We have a $text operator that searches the two words “Mangoes” and “Orange” with the help of a $search operator. Then, we have a projection {score: $meta: “textScore”} which makes use of the $meta operator, which returns specified metadata from retrieved documents. The textScore metadata, which is a built-in component of MongoDB’s full-text search engine and holds the search relevance score, is returned in this case.

As mentioned in the filter document, the resulting documents will add a new field named score after executing the query:

Now, we have used sort function for the projection {score: $meta: “textScore”}. The sorting document uses the same syntax as the projection document.

The text mango has the greatest relevancy score, so it comes first on the output screen.

Conclusion:

We have acquired how to use MongoDB’s full-text search functionalities by following this tutorial. You built a text index and composed text search queries that included one and many words, entire phrases, and exclusions. You’ve also graded the relevance of the returned papers and ordered the search results to display the most relevant items first.



Source link


“Node.js is a JavaScript environment used as a free server environment that keeps running on the V8 engine and different operating systems like Windows, Linux, MacOS, etc. Because of its solitary essence, Node.js is best suited to non-blocking, task-driven data centers. It was created with genuine, push-based frameworks in the head, which are used for conventional sites and back-end API facilities. We will be using it to connect the MongoDB database with the cloud MongoDB server via the Ubuntu 20.04 Linux system in this article. So, let’s take a look now. Let’s start with the Linux system update for the successful implementation of this article. Thus, we have been trying the sudo apt-get command for update via the sudo rights. It may ask for the password of a currently working Linux user. You have to add the password to proceed.”

After updating your Linux system, you have to install the software-properties-common bundle that contains the set of different repositories used to install different software via the Ubuntu 20.04 shell. To install this, you need to try out this installation command with the apt-get keyword.

After the installation of necessary packages and modules for further installation, we will be moving towards the installation of an “npm” package manager for Nodejs first. To install it, try out the apt-get installation instruction along with the keyword “npm.” Add your password, if asked at the shell, and continue.

Tap “y” to continue moving forward in the processing upon being asked: “Do you want to continue?”.

Wait until the progress reaches 100 percent on the processing of this query. You can also try out the same command with the keyword “nodejs,” as shown below.

After the successful installation of the “npm” package, we will be installing the Nodejs JavaScript environment package on our Ubuntu 20.04 system with the “apt-get” package in the installation instruction. Make certain to indulge the “sudo” privileges to do so. Use the keyword “nodejs” in the command. It will be installed in no more than 2 minutes.

Let’s check out the “npm” version just installed at our end with the version command. So we have been using the keyword “npm” with the “-v” option and got version 6.14.4.

To check if the nodejs has been successfully installed in our system, we need to use the dpkg command with the –get-selections option. It will list down all the mounted packages.

Roll down a little, and you will see “nodejs” in this list.

It’s time to install “MongoDB” at our end with the use of the “npm” package at the shell. So, we have tried the installation command with the keyword “MongoDB” via the “npm” package. Wait until it collects the information and install it fully.

After the installation, it will show the following output, i.e., the installed version of MongoDB. It is also stating that 3 packages might require funding to fully configure them.

You can also try out the “npm” package within the list command along with the keyword “MongoDB” to display the versions of MongoDB installed by the “npm” package. Right now, we have only one version of mongo dB installed on our system, i.e., 4.6.0.

After the successful configurations of npm, nodejs, and mongo dB at the Ubuntu 20.04 Linux system, it’s time to set up the cloud server now. So, you need to open the MongoDB cloud site in your browser and register from the authenticated email. After the successful registration, log in from the cloud MongoDB and create a new cluster. You need to select the location while creating a cluster and label it. For instance, we have named it “test,” as you can see from the “All Clusters” page.

Tap on the cluster name “test” to see its data and servers. You have to make a new user and its password for this cluster “test.” To connect the Linux machine with the cloud server, you need to add the IP address of your Linux machine to the Database Access panel and save it. We have created a user name with “saeed” and given it a new password. You need to create a new database in the cloud as well.

We have created a database “test” and added a new collection “Data” within it. Within the “Data” collection, we have added a single record for columns “id” and “title.” The shown-below output is all about your test server. Tap on the “connect” button shown on your below screen to connect this cloud server with the Linux system via Nodejs. You will be provided with 3 different ways to connect your cloud server with the almacén database, i.e., via terminal shell, via the application, and others. Copy the URL provided to connect a almacén database with the cloud server. Note that the URL will be different according to the Nodejs versions.

Create a new JavaScript file using the touch instruction, i.e., node.js. Add the shown-below code within it. The variable “URL” must contain the copied URL from the cloud. Add your username and password for the “test” server within this URL provided and paste it. This JavaScript code will be used to connect the “test” database of MongoDB with the cloud and display the data of collection “Data” at the shell. If the connection got unsuccessful, it would throw an error.

If you have tried the above code for connectivity, run the node.js file at the shell using the “node” command as shown.

You can also use the URL provided for the option of connecting through the MongoDB shell, as shown.

Conclusion

This tutorial briefly illustrates using the Nodejs to find the MongoDB cloud server data at the almacén server. You need to create an account on a cloud server, generate a new database and its collection, and add a username, password, and Ip address. After that, you need to use the URL provided at your cloud on the MongoDB shell or Nodejs file to connect. The database collection data will be displayed at the shell, i.e., added in the cloud database and shown on the almacén MongoDB shell.



Source link