NO SQL - Mongodb 101
Published: 2023-01-28 12:44:07



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5mzhjluqqhcgjb2b2zqn.png)


For installation in Ubuntu 22:

https://wiki.crowncloud.net/How_To_Install_Duf_On_Ubuntu_22_04?How_to_Install_Latest_MongoDB_on_Ubuntu_22_04

CRUD Operations:
https://www.mongodb.com/docs/manual/crud/

        db.help()                    help on db methods
	db.mycoll.help()             help on collection methods
	sh.help()                    sharding helpers
	rs.help()                    replica set helpers
	help admin                   administrative help
	help connect                 connecting to a db help
	help keys                    key shortcuts
	help misc                    misc things to know
	help mr                      mapreduce

	show dbs                     show database names
	show collections             show collections in current database
	show users                   show users in current database
	show profile                 show most recent system.profile entries with time >= 1ms
	show logs                    show the accessible logger names
	show log [name]                                  prints out the last segment of log in memory, 'global' is default
	use <db_name>                                    set current database
	db.mycoll.find()                                     list objects in collection mycoll
	db.mycoll.find( { a : 1 } )                      list objects in mycoll where a == 1
	it                                                                   result of the last line evaluated; use to further iterate
	DBQuery.shellBatchSize = x               set default number of items to display on shell
	exit                                                             quit the mongo shell


Collections:
A collection in MongoDB is a group of documents.
Collections in a NoSQL database like MongoDB correspond to tables in relational database management systems (RDBMS) or SQL databases.  As such, collections don’t enforce a set schema, and documents within a single collection can have widely different fields.




BASIC:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9gtsfq2dxvo4mc2iabhu.png)

1. mongo
2. show dbs
3. use showDB
4. show collections
5. db.products.find()

VIEW:
If users collection doesnt exist in the database, then it will create a new one.
To view a collection in MongoDB, you can use the find() method on the collection. This method returns a cursor to the documents in the collection, which you can then iterate through to display the documents.

For example, if you have a collection named "users" in a MongoDB database, you can view the documents in that collection using the following command in the MongoDB shell:

```
db.users.find()
```

This will return all documents in the "users" collection. If you want to see specific documents, you can pass a query document to the find() method.

```
db.users.find({"age": 25})
```

This will return all documents in the "users" collection where the "age" field is equal to 25.

You can also use the cursor returned by find() to iterate through the documents, and get more options like limit, skip

```
var cursor = db.users.find(); 
cursor.forEach(printjson);
```

This will display the documents one at a time, using the printjson() function to pretty-print each document.

UPDATE:
To update a document in MongoDB, you can use the updateOne() or updateMany() method on the collection. The updateOne() method updates the first document that matches a specified filter, while the updateMany() method updates all documents that match a specified filter.

For example, if you have a collection named "users" in a MongoDB database, you can update a document with the following command in the MongoDB shell:

```
db.users.updateOne(    { "name" : "John Doe" },    { $set: { "age": 30 } } );
```

This updates the first document in the "users" collection where the "name" field is "John Doe" and sets the "age" field to 30.

You can also use the updateMany() method to update multiple documents that match a specified filter:

```
db.users.updateMany(    { "age": 25 },    { $inc: { "age": 5 } } );
```

This updates all documents in the "users" collection where the "age" field is equal to 25 and increments the "age" field by 5.



Signifiance of _id:
In MongoDB, every document stored in a collection has a unique identifier called the _id. This field is automatically added by MongoDB if one is not specified when inserting the document. The _id serves as the primary key for the document and is used for indexing and sharding. It is also used to ensure that every document in a collection is unique and can be efficiently retrieved using this field. It can be any type of value, but is typically a 12-byte ObjectId or a string.

can you have two  same _id field in two different documents in two different collections:
In MongoDB, the _id field is a unique identifier that is automatically generated for each document when it is inserted into a collection. This means that the _id value is unique within a single collection.

However, it is possible to have two documents with the same _id value in different collections. This is because the uniqueness constraint for the _id field only applies within a single collection and not across collections.

For example, if you have two collections "users" and "employees" both can have a document with the same _id value, such as:

```
db.users.insert({ _id: 1, name: "John Doe" }); 
db.employees.insert({ _id: 1, name: "Jane Doe" });
```

This is possible because both documents are in different collections and MongoDB considers them as separate documents.

It's important to note that while this is possible, it's not always a good practice. It can lead to confusion and make it harder to uniquely identify documents across different collections. It's generally recommended to use a different unique identifier or use a combination of fields as a unique identifier to maintain data integrity.

REMOVE  a field:
You can remove a field from a document using the $unset update operator. The $unset operator takes the field name as the key and sets its value to 1, indicating that the field should be removed.

You can use the updateOne() or updateMany() method to remove a field from a document.
Here is an example of how you can use the updateOne() method to remove a field "fieldName" from a document:

```
db.collection.updateOne(    { _id: ObjectId("5f8a12d3c3c74a2e9c8b456b") },    { $unset: { fieldName: 1 } } )
```

And for remove many documents you can use updateMany() method:
```
db.collection.updateMany(    {},    { $unset: { fieldName: 1 } } )
```
This will remove the field named "fieldName" from all the documents in the collection.

INSERT:
In MongoDB, you can insert a document into a collection using the insertOne() or insertMany() method.

Here is an example of how you can use the insertOne() method to insert a document into a collection named "collection":

```
db.collection.insertOne({
    _id: ObjectId("5f8a12d3c3c74a2e9c8b456b"),
    fieldName: "value",
    fieldName2: "value2" 
});
```

And for insert many documents at once you can use insertMany() method :

```
db.collection.insertMany([
    { _id: ObjectId("5f8a12d3c3c74a2e9c8b456b"), fieldName: "value1" },
    { _id: ObjectId("5f8a12d3c3c74a2e9c8b456c"), fieldName: "value2" },
    { _id: ObjectId("5f8a12d3c3c74a2e9c8b456d"), fieldName: "value3" } 
]);
```

REMOVE:

To remove a document from a collection, you can use the deleteOne() or deleteMany() method.

Here is an example of how you can use the deleteOne() method to remove a document with a specific _id from a collection named "collection":

```
db.collection.deleteOne({ _id: ObjectId("5f8a12d3c3c74a2e9c8b456b") });
```

And for removing many documents you can use deleteMany() method:

```
db.collection.deleteMany({ fieldName: "value" });
```

This will remove all the documents where the field named "fieldName" has the value "value" from the collection.
It's important to note that the deleteOne() method will remove only one matching document, while the deleteMany() method will remove all the matching documents. Also, if you don't pass any query to the delete methods, it will remove all the documents in the collection


FIND queries:
There are several different types of queries that can be added to the find() method in MongoDB to filter the results. Some examples include:

1. Equality match: {field: value}
   example: db.collection.find({age: 25})
2. Comparison operators: {field: {$gt: value}}
   example: db.collection.find({age: {$gt: 20}})
3. Logical operators: {$or: [{field: value}, {field: value}]}
   example: db.collection.find({$or: [{age: 25}, {name: "John"}]})
4. Existence: {field: {$exists: true/false}}
   example: db.collection.find({age: {$exists: true}})
5. Regex: {field: {$regex: /pattern/}}
   example: db.collection.find({name: {$regex: /^J/}})
6. Combining multiple conditions: {field: value, field: value}
   example: db.collection.find({age: {$gt: 25}, gender: "male"})

These are just a few examples of the types of queries that can be added to the find() method. MongoDB has many more options for querying data, including the use of projection, sorting, and limiting the number of results returned.

Comparision operators:
Comparison operators in MongoDB can be used to compare the values of fields in documents and filter the results of a query. Some common comparison operators include:

1. $eq: Matches values that are equal to a specified value.
   example: db.collection.find({age: {$eq: 25}})
2. $gt: Matches values that are greater than a specified value.
   example: db.collection.find({age: {$gt: 25}})
3. $gte: Matches values that are greater than or equal to a specified value.
   example: db.collection.find({age: {$gte: 25}})
4. $lt: Matches values that are less than a specified value.
   example: db.collection.find({age: {$lt: 25}})
5. $lte: Matches values that are less than or equal to a specified value.
   example: db.collection.find({age: {$lte: 25}})
6. $ne: Matches all values that are not equal to a specified value.
   example: db.collection.find({age: {$ne: 25}})
7. $in: Matches any of the values specified in an array.
   example: db.collection.find({age: {$in: [25, 30, 35]}})
8. $nin: Matches none of the values specified in an array.
   example: db.collection.find({age: {$nin: [25, 30, 35]}})

These are just a few examples of the comparison operators that are available in MongoDB. You can use these operators in combination with other query operators to filter the results of a query more precisely.

Logical operators:
Logical operators in MongoDB can be used to combine multiple query conditions and filter the results of a query. Some common logical operators include:

1. $and: Matches all documents that match both of the specified query conditions.
   example: db.collection.find({$and: [{age: {$gt: 25}}, {gender: "male"}]})
2. $or: Matches all documents that match at least one of the specified query conditions.
   example: db.collection.find({$or: [{age: {$lt: 25}}, {gender: "female"}]})
3. $not: Matches all documents that do not match the specified query condition.
   example: db.collection.find({age: {$not: {$gt: 25}}})
4. $nor: Matches all documents that fail to match both of the specified query conditions.
   example: db.collection.find({$nor: [{age: {$lt: 25}}, {gender: "female"}]})

These logical operators can be used to filter the results of a query by combining multiple conditions. You can use these operators in combination with other query operators to filter the results of a query more precisely.

Existence:
The $exists operator in MongoDB can be used to check whether a field in a document exists or not. This operator can help you to filter out documents that have or don't have a certain field.

1. $exists: true: Matches documents that contain the specified field.
   example: db.collection.find({age: {$exists: true}})
2. $exists: false: Matches documents that do not contain the specified field.
   example: db.collection.find({age: {$exists: false}})

For example, you can use this operator to find all documents that have a field called "age" with a value of {$exists: true} and documents that don't have the "age" field with a value of {$exists: false}
You can also use this operator in combination with other query operators to filter the results of a query more precisely.
Note: It's also possible to check for the existence of fields inside sub-documents using dot notation.

example: 
db.collection.find({"address.zipcode": {$exists: true}})

It's also worth mentioning that, If you want to check for the existence of a field in an array, you can use the $elemMatch
 operator.

example: 
db.collection.find({hobbies: {$elemMatch: {$exists: true}}})

REGEX:
The $regex operator in MongoDB can be used to perform a regular expression search on string fields in a document. This operator allows you to filter documents based on a pattern or a set of patterns in a field's value.

Here is an example of how you can use the $regex operator to find documents that have a field called "name" with a value that starts with "J":

```
db.collection.find({name: {$regex: /^J/}})
```

You can also use the $options operator to specify options for the regular expression search. For example, you can use the "i" option to perform a case-insensitive search:

```
db.collection.find({name: {$regex: /^j/, $options: "i"}})
```

Here are some more examples of the usage of $regex:

1. Matches any string that contains the word "example"
   example: db.collection.find({name: {$regex: /example/}})
2. Matches any string that starts with "J" and ends with "n"
   example: db.collection.find({name: {$regex: /^J.*n$/}})
3. Matches any string that contains a number
   example: db.collection.find({name: {$regex: /\d/}})

You can use the $regex operator in combination with other query operators to filter the results of a query more precisely.

Note: Be aware that Regular expressions can be computationally expensive, especially when querying large datasets or using complex regular expressions.

Combining multiple conditions:
```
db.collection.find({
     $and: [
         {age: {$gt: 25}},
         {$or: [
             {gender: "male"},
             {gender: "female"}
         ]}
     ]
 })        
```

This query will return all documents in the collection that have an "age" field greater than 25 and a "gender" field with the value of "male" or "female".

You can combine multiple conditions to create a query that filters the results of a query as precisely as possible. It's also possible to use logical operator $not or $nor for negation.

It's worth noting that, You have to be careful when using multiple conditions and logical operators, as it can affect the performance of your query if not used efficiently.

BSON:
JSON (JavaScript Object Notation) and BSON (Binary JSON) are both data formats that are used to represent and store data in a structured way. However, there are some key differences between the two:

1. Binary representation: BSON is a binary-encoded serialization of JSON-like documents. This means that BSON stores data in a binary format, whereas JSON stores data in a plain text format. This makes BSON more space-efficient and faster to parse, but it also means that BSON documents cannot be easily read or edited by humans.
2. Data types: BSON supports a wider range of data types than JSON. For example, BSON includes support for binary data, timestamp, and 64-bit integers, whereas JSON only includes basic data types such as strings, numbers, and Booleans.
3. Size: BSON documents are typically smaller in size than equivalent JSON documents due to its binary encoding.
4. Use cases: JSON is primarily used for sending and receiving data over the internet, while BSON is primarily used for storing data in a MongoDB database. MongoDB uses BSON to represent documents within a collection and the BSON format is also used when storing data on disk or in memory.
5. Compatibility: JSON is widely supported and can be easily used with many programming languages and platforms, whereas BSON is primarily used in the MongoDB ecosystem. BSON can be converted to and from JSON, so it can be easily integrated with other systems that use JSON.

In summary, JSON and BSON are both data formats that are used to represent and store data in a structured way. JSON is primarily used for sending and receiving data over the internet, while BSON is primarily used for storing data in MongoDB. BSON is more space-efficient and faster to parse, but it is not as human-readable as JSON.

RELATIONSHIPS:

<one to one>

```
//Collection "users"
{
    "_id": ObjectId("5f20d0a45f24a8c8e4ab2e9c"),
    "name": "John Smith",
    "email": "johnsmith@gmail.com"
}

//Collection "orders"
{
    "_id": ObjectId("5f20d0a45f24a8c8e4ab2e9d"),
    "user": ObjectId("5f20d0a45f24a8c8e4ab2e9c"),  // this is the link
    "item": "Apple iPhone",
    "quantity": 2,
    "price": 800
}
```

<one to many>
```
//Collection "users"
{
    "_id": ObjectId("5f20d0a45f24a8c8e4ab2e9c"),
    "name": "John Smith",
    "email": "johnsmith@gmail.com"
}

//Collection "posts"
{
    "_id": ObjectId("5f20d0a45f24a8c8e4ab2e9d"),
    "user": ObjectId("5f20d0a45f24a8c8e4ab2e9c"),  // this is the link
    "title": "My first post",
    "content": "This is my first post on my blog."
},
{
    "_id": ObjectId("5f20d0a45f24a8c8e4ab2e9e"),
    "user": ObjectId("5f20d0a45f24a8c8e4ab2e9c"),  // this is the link
    "title": "My second post",
    "content": "This is my second post on my blog."
}
```

<many to many>
```
//Collection "users"
{
    "_id": ObjectId("5f20d0a45f24a8c8e4ab2e9c"),
    "name": "John Smith",
    "email": "johnsmith@gmail.com"
},
{
    "_id": ObjectId("5f20d0a45f24a8c8e4ab2e9d"),
    "name": "Jane Doe",
    "email": "janedoe@gmail.com"
}

//Collection "posts"
{
    "_id": ObjectId("5f20d0a45f24a8c8e4ab2e9e"),
    "title": "My first post",
    "content": "This is my first post on my blog.",
    "users": [
        ObjectId("5f20d0a45f24a8c8e4ab2e9c"),
        ObjectId("5f20d0a45f24a8c8e4ab2e9d")
    ]  // this is the link
},
{
    "_id": ObjectId("5f20d0a45f24a8c8e4ab2e9f"),
    "title": "My second post",
    "content": "This is my second post on my blog.",
    "users": [
        ObjectId("5f20d0a45f24a8c8e4ab2e9c")
    ]  // this is the link
}
```

Filtered linkage:
```
// Find all the orders that belong to the user with _id = "5f20d0a45f24a8c8e4ab2e9c" and have a price greater than 100
var userId = ObjectId("5f20d0a45f24a8c8e4ab2e9c");
var orders = db.orders.find({ userId: userId, price: { $gt: 100 } });

// Extract the _id of each order
var orderIds = orders.map(function(order) { return order._id });

// Use the $filter operator to add the orders to the user document
db.users.updateOne(
    { _id: userId },
    { $push: { orders: { $each: [{ $filter: { input: orderIds, as: 'order', cond: { $gt: ['$$order.price', 100] } } }] } } }
);
```