jueves, 17 de octubre de 2019

MongoDB: Comandos básicos de mongo shell

Una vez que hemos instalado MongoDB en nuestro PC, podemos empezar a manejar la base de datos:

Primero abrimos la consola de JavaScript mongo shell:


Ahora podemos empezar a manejar la base de datos mediante comandos.

ALTA

Primero vamos a dar de alta una colección "users" e insertamos dos usuarios con los siguientes comandos:
db.users.insert({"name": "francesco","age": 44, "phone": "123-567-890"})
db.users.insert({"name": "owen","age": 32, "phone": "555-444-333"})

CONSULTA

Ahora buscamos todos los usuarios de la colección users:
db.users.find()

Contamos todos los registros de la colección users:
db.users.count()

Buscamos, en la colección users, un usuario cuyo nombre sea owen:
db.users.find({"name": "owen"})

Buscamos, en la colección users, un usuario cuyo nombre sea owen y cuya edad sea 32:
db.users.find({"name": "owen", "age": 32})

Mostramos, de la colección users, sólo los campos nombre y edad:
db.users.find({}, {"name": 1,"age": 1})

Mostramos, de la colección users, todos los campos menos el nombre y la edad:
db.users.find({}, {"name": 0,"age": 0})
Note that you cannot have a mix of inclusions and exclusions in your projection. The exception to the rule is the _id field. In fact, {_id: 0, name: 1, age: 1} works but any inclusion/exclusion combination of other fields does not.

Operators: The equivalent operators in MongoDB terms are $gt, $gte, $lt, and $lte.
Mostramos, de la colección users, los usuarios cuya edad sea mayor de 40:
db.users.find({ age: { $gt: 40 } })

Mostramos, de la colección users, los usuarios cuya edad sea mayor o igual a 32:
db.users.find({ age: { $gte: 32 } })

Mostramos, de la colección users, los usuarios cuya edad sea menor de 35 o cuyo nombre sea john:
db.users.find( { $or: [ { "age": { $lt: 35 } }, { "name": "john" } ] } )

Mostramos, de la colección users, los usuarios cuya edad sea menor de 35 y cuyo nombre sea john:
db.users.find( { $and: [ { "age": { $lt: 35 } }, { "name": "john" } ] } )

By using the NOT operator, you can invert the effect of a query expression and return documents that do not match the query expression. For example, if you wanted to query for all users with last names not beginning with f, you could  use $not as follows:
db.users.find({"name": {$not: /^f/} })

Using LIKE in Mongo Note the /expr/ operator, which can be used to achieve a SQLlike equivalent expression. For example, in its simplest form, you can use it to query for phone numbers, which are like 444:
db.users.find({"phone": /444/})

MODIFICACIÓN

Modificamos la edad del usuario owen a 39:
db.users.update({name: "owen"}, {$set: {"age": 39}})
Be aware that executing an update without the $set operator won't update the fields but replace the whole document, while preserving the _id field.

The update supports an additional option, which can be used to perform a more complex logic. For example, what if you wanted to update the record if it exists, and create it if it doesn't? This is called upsert and can be achieved by setting the upsert option to true, as in the following command line:
db.users.update({user: "frank"}, {age: 40},{ upsert: true} )

Updating a document with MongoDB can be done also on a portion of a document, for example, you can remove a single key from your collection by using the $unset option. In the following update, we are removing the age key to all documents whose name key equals to owen.
db.users.update({name: "owen"}, {$unset : { "age" : 1} })

The opposite of the $unset operator is $push, which allows you to append a value to a specified field. So here is how you can restore the age key for the user owen:
db.users.update({name: "owen"}, {$push : { "age" : 39} })
You can achieve the same result by using $set on a field, which is not included in the document.

BAJA

When used without any parameter, it is equivalent to the TRUNCATE command in SQL terms:
db.users.remove()

Eliminamos a los usuarios cuya edad sea mayor de 40:
db.users.remove({ "age": { $gt: 40 } })

Just like the TRUNCATE statement in SQL, it just removes documents from a collection. If you want to delete the collection, then you need to use the drop() method, which deletes the whole collection structure, including any associated index:
db.users.drop()

ALTA ARRAYS

Insertamos, en la colección restaurante, dos arrays de menú de comida:
db.restaurant.insert({"menu" : ["bread", "pizza", "coke"]})
db.restaurant.insert({"menu" : ["bread", "omelette", "sprite"]})

We will now show you how to query on the array selection to find the menu, which includes pizza:
db.restaurant.find({"menu" : "pizza"})

Buscamos los menús que contengan tanto pizza como coke:
db.restaurant.find({"menu" : {$all : ["pizza", "coke"]}})

EMBEDDED DOCUMENTS

Let's start by defining a structure, which is assigned to a variable in the mongo shell:
x = {
    "_id":1234,
    "owner":"Frank's Car",
    "cars":[
        {
            "year":2011,
            "model":"Ferrari",
            price:250000
        },
        {
            "year":2013,
            "model":"Porsche",
            price:250000
        }
    ]
}
Having defined our variable, we can insert it into the cars collection as follows:
db.cars.insert(x);

We can query our subdocument by using the dot notation. For example, we can choose the list of cars whose model is Ferrari by using the cars.model criteria:
db.cars.find( { "cars.model": "Ferrari" }).pretty()
Also, the pretty function provides a pretty formatted JSON in the response.

FUNCIONES ÚTILES

You can use the limit function to specify the maximum number of documents returned by your query. You obviously need to provide the number of records to be returned as a parameter. By setting this parameter to 0, all the documents will be returned:
db.users.find().limit(10)

The sort function, on the other hand, can be used to sort the results returned from the query in ascending (1) or descending (-1) order. This function is pretty much equivalent to the ORDER BY statement in SQL. Here is a basic example of sort:
db.users.find({}).sort({"name":1})
This example sorts the results based on the name key-value in ascending order, which is the default sorting order.
Note that the sort function when issued against the document's _id will be sorted on a time criteria.

The next one in the list is the skip function, which skips the first n documents in a collection. For example, here is how to skip the first document in a search across the users collection:
db.users.find().skip(1)

All the preceding commands can be also combined to produce a powerful expression. For example, the preceding command will return a different user  when combined with a sort function in descending order:
db.users.find().skip(1).sort({"name":-1}

No hay comentarios:

Publicar un comentario