Truy vấn cập nhật MongoDB Compass

--- tags. ironhack, lecture, ---

![Ironhack Logo](https://i.imgur.com/1QgrNNw.png) # Mongo | Mongo Compass CRUD Operations ## Learning goals After this lesson, you will be able to: - Import a database into Mongo - Understand how to update and remove documents from your database using Mongo Compass - Learn how to query documents using equality conditions - Understand how the `$and`, `$or`, `$ne`, `$nor` operators work - Learn about Mongo Compass query Options such as projections, sort, limit and skip - Understand elements, array, and comparison query operators. - Understand how to implement advanced query operators. ## Intro ![](https://i.imgur.com/NzalR30.png) :::info lecture CRUD ::: When working with any Database, there are a few operations that we will always need to use. These operations are so popular that we have an acronym for it: [CRUD](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete) stands for `create`, `read`, `update` and `delete`: ![](https://i.imgur.com/CRowB2i.png) These are the basic operations to persist data in our Database, and with them, we can do anything we want. Ready? ## Importing Data :::info lecture Pour importer une base de données entière, nous allons avoir recours au programme `mongoimport` installé avec mongodb. ::: We learned how to add new documents to our database, but sometimes we will need to import data into our database. Mongo includes a tool named `mongoimport` to help us with this. The `mongoimport` imports content from [JSON](https://www.json.org/), [CSV](https://en.wikipedia.org/wiki/Comma-separated_values) or [TSV](https://en.wikipedia.org/wiki/Tab-separated_values) files. Every time we need to use `mongoimport`, we should run it from the system command line (That means the terminal :wink:) ### Example In the following example, `mongoimport` imports the JSON data from the `contacts.json` file into the collection contacts in the user's database. ```bash $ mongoimport --db users --collection contacts --file contacts.json ``` ### Our database For this lesson, we will use the **`video`** database that includes a `movies` collection with 250 documents of the Top 250 movies of all times according to [IMDB](http://www.imdb.com/?ref_=nv_home) Download the `.zip` file from [here](https://s3-eu-west-1.amazonaws.com/ih-materials/learning-units/movies.json.zip), and then run the following commands: :::info lecture Importons nos données depuis [le fichier zip](https://s3-eu-west-1.amazonaws.com/ih-materials/learning-units/movies.json.zip) avec `mongoimport` : - nom de la database : `video` - nom de la collection : `movies` ::: ```bash $ cd ~/Downloads $ unzip movies.json.zip $ mongoimport --db video --collection movies --file movies.json --jsonArray ``` :::info You should be in the folder where you download the `.zip` file. ::: ## Compass Schema If our `mongoimport` went ok, we should be able to see our database **video** with the **movie** collection in MongoCompass. :::info lecture Vérifions en cliquant sur la collection `movies` que tous nos documents sont bien présents en base : ::: ![image](https://user-images.githubusercontent.com/23629340/34391000-7f811a90-eb43-11e7-89cd-353a4bba11d9.png) :::info lecture Une option intéressante de Compass : Schema tab > Analyse schema : ::: If we click on movies, it should navigate to the **Documents** view. There we should click on the **Schema** tab, and then **Analyze Schema**. ![image](https://user-images.githubusercontent.com/23629340/34391039-d3100b4e-eb43-11e7-87b6-bb903b813b42.png) The **Schema** tab reports on the documents in the collections. If there are too many documents, a sampling of them is the base for it. ### Charts :::info lecture On peut dès lors avoir une vue macro de nos données et inspecter tant leurs types que leurs valeurs. ::: For a field, Compass displays the data types and values with various charts. The data type information is on the left-hand side; the field value information is on the right. #### Field with Single Type Values Below is an example of a chart showing a field called `duration` which contains data of type `string`. ![image](https://user-images.githubusercontent.com/23629340/34391313-135bf842-eb45-11e7-91d7-754d278d64fa.png) #### Field with Multiple Type Values The charts also display a percentage breakdown for fields with varying data types across documents. In the example below, it shows the contents of the `year` in which 98% of documents are of type `string`, and the remaining 2% are of type `double`. ![image](https://user-images.githubusercontent.com/23629340/34391375-754548ce-eb45-11e7-99c5-5eb53d17960b.png) #### Missing Field If a collection contains documents in which not all fields contain a value, the missing values display as undefined. In the example below, the field age has no recorded value in 40% of the sampled documents. ![image](https://user-images.githubusercontent.com/23629340/34391393-94073a42-eb45-11e7-8dc5-3f5041ca18bd.png) ## Update Documents :::info lecture Nous pouvons modifier un document grace à l'icon :pencil2:. Mettons par ex à jour la note d'un film : ::: To edit a document is pretty simple, we just need to hover over the document and select the pencil icon: ![image](https://user-images.githubusercontent.com/23629340/34403215-41efaa02-eba7-11e7-8115-0b98eff01a31.png) After you click the pencil icon, the document will enter in edit mode. Here you can make changes to the fields, values or data type. ![image](https://user-images.githubusercontent.com/23629340/34403190-1d2a46d2-eba7-11e7-86ad-f79908e76884.png) When you finish, click on the **UPDATE** button on the bottom right, and is done! ### Delete fields :::info lecture On peut également supprimer un champ entier grace à l'icon :heavy_multiplication_x:. Il sera ensuite rouge, jusqu'à ce qu'on clique sur le bouton `Update`. ::: You can delete fields by selecting the **x** icon to the left of the field: ![image](https://user-images.githubusercontent.com/23629340/34403291-b2f463aa-eba7-11e7-9116-34e5ee08aac4.png) Once selected, the field is marked for removal and appears highlighted in red: ![image](https://user-images.githubusercontent.com/23629340/34403295-b9576a08-eba7-11e7-9195-e1cb2c379fe8.png) ### Add new fields :::info lecture Il est également possible d'ajouter un champ : - soit en cliquant sur l'icon + du début de ligne - soit en faisant un retour a la ligne apres le dernier champ ::: To insert a new field, click or tab to the end of the document and fill in the field/value. New fields appear highlighted in green: ![image](https://user-images.githubusercontent.com/23629340/34403310-d28f391a-eba7-11e7-8b5a-0d5633b05baa.png) To add a new field to the document, hover over the row number in the dialog and click on the plus sign to add a new one. You can also add a new field at the end by hitting the Tab from the value of the last one. ## Delete Documents :::info lecture Nous pouvons également supprimer des documents de notre collection, grace à l'icon 🗑 ::: From the Documents view, you can delete documents by hovering over the document and selecting the trash icon: ![image](https://user-images.githubusercontent.com/23629340/34403356-ff1cc948-eba7-11e7-9681-25048dd880b7.png) After clicking the delete button, Compass flag the document for deletion and then asks for confirmation that you want to remove the document: ![image](https://user-images.githubusercontent.com/23629340/34403362-0524abb2-eba8-11e7-8db7-908252b5ab52.png) After you confirm, Compass deletes the document from the collection. ## Read Documents :::info lecture Au dela de lister l'ensemble des documents, nous allons vouloir pouvoir rechercher certains en particulier. Pour cela, **nous allons effectuer une requete (aka query)**. ::: For reading documents, we can navigate through the **Documents** tabs and check all of them. But when we have hundreds and hundreds of documents this is not efficient at all if we are looking for a specific one. For that purpose we have [queries](https://www.thoughtco.com/query-definition-1019180). When we want to find a subset of documents from our database, we `query` the database. This means that we will ask the database, using a **query language**, which conditions we need to get that subset of data. Let's see how that works on MongoCompass. ### Query Bar On any collection, at the **Documents** tabs you can use the query bar to specify Mongo queries. :::info lecture L'écriture de notre requete se fera via la query-bar, disponible dans chaque collection : ::: ![image](https://user-images.githubusercontent.com/23629340/34410103-305e155e-ebce-11e7-9d20-37d22e8aa201.png) ### Filter - Basic Query The most basic Mongo query is to specify an equality condition. To write this query you must use **{ `field` : `value` }** expression. For example, if we want to search for documents with the value **"The Godfather"** on the **title** field, we should do something like this and then click on "Find" button: :::info lecture Recherchons les films dont le titre est (Strictement) égal à `"The Godfather"`: ``` {title: "The Godfather"} ``` ::: ![image](https://user-images.githubusercontent.com/23629340/34410214-e5ad592e-ebce-11e7-811b-7dbf6ad833ed.png) :::info As you type, the Find button is disabled, and the Filter label turns red until you enter a valid query. This feature will help us know our query is valid! ::: ### ObjectId() :::info lecture On peut également rechercher un film par son ID : ``` {_id: ObjectId('5dcee9ecc47f733dcb6e4a03')} ``` ::: Filter by an **ObjectId** is tricky. Since the **ObjectId** is store as a data type `ObjectId` we should specify we are looking for one. Otherwise, Mongo Compass will search for the value as a `string`. To specify an **ObjectID**, use the format **ObjectId('`id`')**, as in the following filter example: ![image](https://user-images.githubusercontent.com/23629340/34410324-a6960528-ebcf-11e7-8d1c-df81829b7fbc.png) ### Query with Logical Operators: `$and`, `$or`, `$ne`, `$nor` :::info lecture Nous allons pouvoir complexifier nos requetes grâce à des opérateurs. ::: #### `$and` conditions A compound query can specify conditions for more than one field in the collection’s documents. Implicitly, a logical **AND** conjunction connects the clauses of a compound query and selects the ones that match all the conditions. The **`$and`** has the following syntax: ```bash { $and: [ {}, {}, .. {} ] } ``` :::info lecture Pour trouver les films de l'an `2000` **ET** notés `8.5` : ``` { $and: [ {year: '2000'}, {rate: '8.5'} ] } ``` NB: `$and` prend une liste ::: The following examples retrieve all documents in our collection where the field `year` equals `'2000'` **AND** the `rate` equals `'8.5'`. ![image](https://user-images.githubusercontent.com/23629340/34410408-5fda0f70-ebd0-11e7-8113-9c5d7aa786dc.png) #### `$or` conditions Using the `$or` operator, you can specify a compound query that joins each clause with a logical OR conjunction that selects the documents in the collection that match at least one condition. The **`$or`** has the following syntax: ```bash { $or: [ {}, {}, .. {} ] } ``` The following examples retrieve all documents in our collection where the field `year` equals `'2000'` **OR** the `rate` equals `'8.5'`. :::info lecture Pour trouver les films de l'an `2000` **OU BIEN** notés `8.5` : ``` { $or: [ {year: '2000'}, {rate: '8.5'} ] } ``` NB: On remarque qu'il y en a plus qu'avec le `$and`, logique ! 😆 ::: ![image](https://user-images.githubusercontent.com/23629340/34410443-b4d7631a-ebd0-11e7-9ca8-beb63eea8e32.png) #### `$nor` conditions The **`$nor`** operator performs a logical **NOR** operation on an array of one or more query expression and selects the documents that fail all the query expressions in the array. The **`$nor`** has the following syntax: ```bash { $nor: [ {}, {}, .. {} ] } ``` :::info lecture Pour trouver les films qui ne sont **ni de l'an 2000 (et en meme temps) ni de `"Sidney Lumet"`** : ``` { $nor: [{year: "2000"}, {director:"Sidney Lumet"}] } ``` NB : les documents qui n'ont pas de champ `year` ni de champ `director` seront retournés. NB : Idem, si un film est de "2000" mais qu'il n'a pas de champ `director`, il sera retourné NB : Idem, si un film est de "Sidney Lumet" mais qu'il n'a pas de champ `year`, il sera retourné ::: ![image](https://user-images.githubusercontent.com/23629340/34411420-c1be8d50-ebd6-11e7-98c4-e3260241897d.png) Running the following query should retrieve documents that: - contain the `year` field whose value is **not equal** to `'2000'` and contain the `director` field whose value is **not equal** to `'Sidney Lumet'`, or - contain the `year` field whose value is not equal to `'2000'` but do not contain the `director` field, or - do not contain the `year` field but contain the `director` field whose value is not equal to `'Sidney Lumet'`, or - do not contain the `year` field and do not contain the `director` field ### Query Projections :::info lecture Les projections, vont nous permettre de sélectionner quels champs des documents il nous intéresse d'avoir dans notre réponse. NB : il nous faut cliquer sur le bouton `options` de la query-bar pour avoir accès aux projections. ![](https://i.imgur.com/Xt27BrM.png) ::: The Find method's second argument, which we mentioned earlier, is called a [projection](https://docs.mongodb.com/v3.2/tutorial/project-fields-from-query-results/), and it allows us to specify which fields returns from each document on the result. ![image](https://user-images.githubusercontent.com/970858/35269300-840a34a8-0023-11e8-9e8c-42df4816b1e2.png) :::info **Using projections makes our database queries faster**. When MongoDB has to retrieve fewer fields, it's less work for the computer to do and less information to transfer over the network, so the query takes less time. To set projections, click **Options**. ::: Let's see how to use the projection. The projection must be an object with either: - All the fields we want to include (set them to `1`) - All the fields we want to exclude (set them to `0`) The projection cannot combine `0` and `1` at the same time except for the `_id` that can be `0` when others are `1`. :::warning By default "_id" is set to `1`, so if we don't want to show it, we have to specify `_id: 0`. ::: For example, if we set the `title` property to **1** and `_id` to **0**, Mongo will return the `title` property of each document, but not their `_id`: :::info lecture Si par ex, ne nous intéresse que le titre : ``` {} {title: 1, _id: 0} ``` NB : `_id` est par défault retourné, on doit le mettre explicitement à 0 si l'on ne le veut pas. ::: ![image](https://user-images.githubusercontent.com/23629340/34411512-52ea27b2-ebd7-11e7-9ff9-f7a9719aebe4.png) ### Sort Query Documents If the query bar has the Sort option, you can specify the sort order of the returned documents. To specify an ascending order for a field, set it to 1 in the sorted document. To establish a descending order, set it to -1 in the sort documents. For example, the following sort document sorts results by title in ascending order. :::info lecture Pour trier nos résultat par titre (AàZ) : ``` {} {} {title: 1} ``` NB : pour le sens inverse (ZàA) `{title: -1}` NB : si plusieurs critères de tri `{title: 1, director: -1}` ::: ![image](https://user-images.githubusercontent.com/23629340/34411590-d6962be2-ebd7-11e7-8acf-cec853df00a8.png) ### Query Documents - Skip & Limit :::info lecture Afin de "paginer" nos résultats, nous pouvons utiliser `skip` et `limit` ::: #### Skip :::info lecture `skip` permet de "sauter" X resultats ::: Using the **Skip** option, you can specify the first n-number of documents to skip before returning the result set. For example, if we want to skip the first 20 documents, we just need to specify the following: ![image](https://user-images.githubusercontent.com/23629340/34411619-16597450-ebd8-11e7-83b1-ff1002ffb17e.png) #### Limit :::info lecture `limit` permet de tronquer la liste à N résultats ::: Using the **Limit** option you can specify the maximum number of documents to return in a query. Here we can make an example of limit the results to 5 documents after skipping 10. ![image](https://user-images.githubusercontent.com/23629340/34411720-f2d69016-ebd8-11e7-9f7b-f2f570f082f0.png) :::info Skip & Limit are two super useful methods to make pagination in our webs. This way we can write queries that only will retrieve the documents we want to show on a specific page, allowing us to retrieve less amount of data on each query and make our webs faster. ::: :::info lecture Ainsi, si l'on veut paginer nos résultat par 100 et afficher la page 3: ``` limit: 100 skip: 200 ``` ::: ## Sample Collection Setup Let's download and import the following JSON file: :::warning https://raw.githubusercontent.com/mongodb/docs-assets/primer-dataset/primer-dataset.json ::: :bulb: In the terminal, use `mongoimport` to import documents into the collection named `restaurants`. :::info lecture Importons une nouvelle base : ::: ``` $ mongoimport --db restaurants --collection restaurants --drop --file primer-dataset.json ``` The following is an example document from the `restaurants` collection. ```javascript { "address": { "building": "1007", "coord": [ -73.856077, 40.848447 ], "street": "Morris Park Ave", "zipcode": "10462" }, "borough": "Bronx", "cuisine": "Bakery", "grades": [ { "date": { "$date": 1393804800000 }, "grade": "A", "score": 2 }, { "date": { "$date": 1378857600000 }, "grade": "A", "score": 6 }, { "date": { "$date": 1358985600000 }, "grade": "A", "score": 10 }, { "date": { "$date": 1322006400000 }, "grade": "A", "score": 9 }, { "date": { "$date": 1299715200000 }, "grade": "B", "score": 14 } ], "name": "Morris Park Bake Shop", "restaurant_id": "30075445", "stars": 4, "reviews": 5, "capacity": 52, "tags": ['awesome place', 'great food', 'good music', 'incredible chef'] } ``` ## Query Operators :::info lecture Nous allons disposer d'autres opérateurs pour requeter nos documents. ::: In past lessons we learn how to find, sort, limit, skip and project using Mongo queries. To do more advanced ones to search elements we want, Mongo gives us some operators. These query operators allow us to find data within the database using the **find** bar. In this lesson we will learn three different types of query operators: - Comparison Query Operators - Array Query Operators - Element Query Operators ## Comparison Query Operators :::info lecture Tout d'abord les opérateurs de comparaison.. ::: ### $eq - Equal The `$eq` method specifies equality condition. The $eq operator matches documents where the value of a field equals the specified value. :::info The `$eq` expression is equivalent to `{ field: value }`. ::: #### Syntax ```javascript { field: { $eq: value } } ``` #### Example Back to our database, if we want to find all the documents which `borough` field is **equal** to `Brooklyn`, we should query the following: :::info lecture Pour rechercher les restaurants du quartier de `"Brooklyn"`: ``` {borough: {$eq: "Brooklyn"}} ``` NB: Ceci est équivalent à `{borough: "Brooklyn"}` plus simple ::: ```javascript { borough : { $eq: "Brooklyn" } } ``` ![image](https://user-images.githubusercontent.com/23629340/34453208-6bfc7ab6-ed4e-11e7-9ce8-f632a4d5a5c8.png) ### $ne - Not Equal `$ne` selects the documents where the value of the field is not equal to the specified value. This operator includes the ones that do not contain the field. #### Syntax ```javascript { field: { $ne: value } } ``` #### Example Consider the following example: :::info lecture Les restaurants autre que de `"Hamburgers"`: ::: ```javascript { cuisine : { $ne: "Hamburgers" } } ``` This query will select all documents in the restaurant's collection where the `cuisine` field value does not equal **"Hamburgers"**, including those that do not contain the `cuisine` field. ![image](https://user-images.githubusercontent.com/23629340/34461517-be97e790-ee2c-11e7-83b1-ceff67c81049.png) ### $gt - Greater Than `$gt` selects those documents where the value of the field is greater than (i.e. `>`) the specified value. For most data types, comparison operators only perform comparisons on fields where the **data type matches the query value’s type.** #### Syntax ```javascript { field: { $gt: value } } ``` #### Example Let's say we want to look for restaurants that have the capacity for at least 40 people; we should write a query like the following: :::info lecture Les restaurants de capacité >40 : NB : pas de champs `capacity` dans notre DB :/ ::: ```javascript { capacity : { $gt: 40 } } ``` #### $gte - Greater Than Equal The query we just did will retrieve all the restaurant that has a capacity of at least 41 because we are asking for the `capacity` to be greater than **40**. We can change the number and set it to **39**, but it's better if we use the `$gte` operator. `$gte` selects the documents where the value of the field is greater than or equal to (i.e. `>=`) a specified value (e.g. value.). So we will have the following query: :::info lecture Les restaurants de capacité >= 40 : ::: ```javascript { capacity : { $gte: 40 } } ``` ![image](https://user-images.githubusercontent.com/23629340/34462053-4ecd67a0-ee3b-11e7-9972-d0581dadca02.png) :::info Notice we add the projection, so we only see `name` and `capacity` fields. You already know how this works! :wink: ::: ### $lt - Less Than On the opposite way, `$lt` selects those documents where the value of the field is lower than (i.e., <>) the specified value. Same as `$gt` for most data types, comparison operators only perform comparisons on fields where the **data type matches the query value’s type.** #### Syntax ```javascript { field: { $lt: value } } ``` #### Example In this case, let's look for restaurants that have the capacity for at less than 20 people because we want a private dinner, so we should write a query like the following: :::info lecture Les restaurants de capacité < 20 : ::: ```javascript { capacity : { $lt: 20 } } ``` ### $lte - Less Than Equal Here we have the same problem that we have when using `$gt`, we will only retrieve restaurants that have a maximum capacity of 19. For including the those who can have 20 people we should use `$lte` operator. `$lte` selects the documents where the value of the field is smaller than or equal to (i.e. <=) a specified value (e.g. value.). So we will have the following query: :::info lecture Les restaurants de capacité <= 20 : ::: ```javascript { capacity : { $lte: 20 } } ``` ![image](https://user-images.githubusercontent.com/23629340/34478697-a8850ee8-efa2-11e7-8546-62517460a577.png) ### Comparison Queries Cheat Sheet :::info lecture résumé ::: | Name | Description | Syntax | | ----- | ----------- | ------ | | $eq | Matches values that are **equal** to a specified value | `{ field : { $eq: value } }` | | $ne | Matches all values that are **not equal** to a specified value | `{ field : { $ne: value } }` | | $gt | Matches values that are **greater than** a specified value | `{ field : { $gt: value } }` | | $gte | Matches values that are **greater than or equal** to a specified value | `{ field : { $gte: value } }` | | $lt | Matches values that are **less than** a specified value | `{ field : { $lt: value } }` | | $lte | Matches values that are **less than or equal** to a specified value | `{ field : { $lte: value } }` | ## Array Query Operators ### $in The `$in` operator selects the documents where the value of a filed equals **ANY (Logical OR)** value in the specified array. If the **field** holds an array, then the `$in` operator selects the documents whose **field** contains at least one element that matches a value in the specified array. #### Syntax ```javascript { field: { $in: [ value1, value2, .... , valueN ] } } ``` #### Example It's Friday night, and we are looking for a great place to eat something so we need to search restaurants that include **great food** or **"incredible chef"** on the `tags` array. If the array includes one of them is enough for us: :::info lecture Les restaurants taggés `"great food"` ou `"incredible chef"` ::: ```javascript {tags: { $in: ["great food", "incredible chef"] } } ``` ![image](https://user-images.githubusercontent.com/23629340/34478674-7c8f9d76-efa2-11e7-809b-c9e12d711085.png) ### $nin The `$nin` operator selects the documents where the **field** value is not in the specified array or the **field** does not exist. #### Syntax ```javascript { field: { $nin: [ value1, value2, .... , valueN ] } } ``` #### Example We hate music too loud, so let's search for restaurants where the tag "too loud" is not included on the `tags` array: :::info lecture Les restaurants dont aucun tag n'est `"too loud"` ::: ```javascript {tags: { $nin: ["too loud"] } } ``` ![image](https://user-images.githubusercontent.com/23629340/34478655-55aa7942-efa2-11e7-87ab-ed3c5d0486b6.png) ### $all The `$all` operator selects the documents where the value of a field is an array that contains all the specified elements. ```javascript { field: { $all: [ value1, value2, .... , valueN ] } } ``` :::warning :bulb: The field in the results will contain all the values we specify BUT can contain others as well! ::: On its behavior, the `$all` operator is equivalent to the `$and` operator we already learn. #### Example We want to search for a restaurant that has both **"great food"** and **"good music"** on the `tags` array. :::info lecture Les restaurants taggés `"great food"` **ET** `"good music"` NB: contrairement à `$in` qui match pour l'un des tags, `$all` les demande tous à la fois. ::: ```javascript {tags: { $all: ["great food", "good music"] } } ``` ![image](https://user-images.githubusercontent.com/23629340/34478646-4037d58c-efa2-11e7-953d-736a5305cca4.png) ### $elemMatch The `$elemMatch` operator matches documents that contain an array field with at least one element that matches all the specified query criteria. If you are going to specify only a single `query` condition, you do not need to use this operator. ```javascript { field: { $elemMatch: {,, .. } } } ``` #### Example Imagine we add a super cool `filter` feature to our app, and we want to filter the restaurants that on the `grades` array have at least one grade "A" and score greater or equal to 15. The `$elemMatch` operator help us with that: :::info lecture Les restaurants ayants dans leur liste de `grades` au moins un grade "A" et de score >= 15 NB: `grades` est un tableau d'éléments ::: ```javascript { grades: { $elemMatch: { grade: "A", score: { $gte: 15 } } } } ``` ![image](https://user-images.githubusercontent.com/23629340/34478620-265040fa-efa2-11e7-9ff5-8baae6e10d37.png) This way, if the document has at least one element on the `grades` array that fit both criteria, it will be included in our filter. ### Array Queries Cheat Sheet :::info lecture résumé ::: | Name | Description | Syntax | | ----------- | ------------------------------------------------------------------------------------------------ | ------ | | $nin | Matches none of the values specified in an array | `{ field: { $in: [ value1, value2, .... , valueN ] } }` | | $in | Matches any of the values specified in an array. | `{ field: { $nin: [ value1, value2, .... , valueN ] } }` | | $all | Matches arrays that contain all elements specified in the query. | `{ field: { $all: [ value1, value2, .... , valueN ] } }` | | $elemMatch | Selects documents if element in the array field matches all the specified $elemMatch conditions. | `{ field: { $elemMatch: {,, .. } } }` | ## Element Query Operators ### $exists When the `$exists` operator is set to **true** it matches the documents that contain the specified field, including the ones where the field value is **null**. When is set to **false** the query returns only those that do not contain the field. #### Syntax ```javascript { field: { $exists:} } ``` #### Example The product manager told us that some restaurants do not display the `capacity` info on the app, and we think is because some documents do not have that info. We need to search those restaurants that do not have the `capacity` field, so this way we can complete them. :::info lecture Les restaurants n'ayant pas de champ `capacity` : ::: ```javascript { capacity: { $exists: false } } ``` ![image](https://user-images.githubusercontent.com/23629340/34478596-09b3c4da-efa2-11e7-97b5-a7e70b56719d.png) ### $type `$type` selects the documents where the value of the field is an instance of the specified **BSON type(s)**. Querying by data type is useful when dealing with highly unstructured data where data types are not predictable. #### Syntax ```javascript { field: { $type:} } ``` You can specify either the **number** or **alias** for the BSON type. The `$type` expression can also accept an `array` of **BSON types** and has the following syntax: ```javascript { field: { $type: [,, .. ] } } ``` The above query will match documents where the field value is any of the listed types. The types specified in the `array` can be either numeric or string aliases. :::info Most common BSON types: | Type | Number | Alias | | ------- | ------ | ------ | | Double | 1 | “double” | | String | 2 | “string” | | Object | 3 | “object” | | Array | 4 | “array” | | ObjectId | 7 | “objectId” | | Boolean | 8 | “bool” | | Date | 9 | “date” | | Null | 10 | “null” | ::: :::info lecture Par ex, les documents ayant un champ `"name"` de type "string": ``` { grades: { $type: "array" } } ``` ::: ### Array Queries Cheat Sheet | Name | Description | Syntax | | ------ | ----------- | ------ | | $exists | Matches documents that have the specified field.| { field: { $exists:} } | | $type | Selects documents if a field is of the specified type.| { field: { $type:} } | ## Summary In this lesson, we learned how to perform basic operations with Mongo Compass, that will help us a lot when manipulating our databases. We also checked how to use some query operators. We learned about elements, arrays, and comparison query operators and how to implement them using Mongo Compass. ## Extra Resources - [Mongo CRUD Documentation](https://docs.mongodb.com/v3.2/crud/) - [Query selectors in MongoDB](https://docs.mongodb.com/v3.2/reference/operator/query/#query-selectors) - [Reference Operators](https://docs.mongodb.com/v3.2/reference/) - [Mongo Compass Querying](https://docs.mongodb.com/compass/master/query-bar/#querying) - [Query Operators](https://docs.mongodb.com/manual/reference/operator/query/) - [Query Operators for Arrays](https://docs.mongodb.com/manual/reference/operator/query-array/) - [Query Operators for Elements](https://docs.mongodb.com/manual/reference/operator/query-element/) - [Query Operators for Comparision](https://docs.mongodb.com/manual/reference/operator/query-comparison/)

Làm cách nào để cập nhật một trường trong MongoDB?

Cập nhật tài liệu cơ bản .
Bước 1) Ra lệnh cập nhật
Bước 2) Chọn điều kiện mà bạn muốn sử dụng để quyết định tài liệu nào cần được cập nhật. .
Bước 3) Sử dụng lệnh set để sửa đổi Tên trường
Bước 4) Chọn Tên trường bạn muốn sửa đổi và nhập giá trị mới cho phù hợp
đầu ra

Làm cách nào để cập nhật MongoDB Compass trong Ubuntu?

truy cập trang web chính thức của MongoDB. Chuyển đến trang tải xuống và chọn phiên bản, nền tảng và loại tệp sẽ tải xuống như trong hình. Điều này sẽ trực tiếp tải tệp xuống thư mục tải xuống của hệ thống của bạn

Làm cách nào để cập nhật dữ liệu người dùng trong MongoDB?

Db . phương thức updateUser() được sử dụng để cập nhật hồ sơ của người dùng trên cơ sở dữ liệu mà bạn chạy phương thức này. Bản cập nhật cho một trường sẽ thay thế hoàn toàn các giá trị của trường trước đó. Điều này bao gồm các bản cập nhật cho mảng vai trò của người dùng.

Làm cách nào để thêm trường mới vào tài liệu hiện có trong MongoDB Compass?

Để thêm trường mới vào tài liệu sau trường hiện có, di chuột qua số hàng trong hộp thoại và nhấp vào dấu cộng . Số hàng không phải là một phần của tài liệu nhưng là một phần của màn hình hộp thoại.