Разберем немного действий с курсором.
db.people.find()
Как мы знаем, с помощью этой функции выводятся все документы существующие в people коллекции. Присвоим переменной cur значение этой функции:
cur = db.people.find()
Теперь мы можем выполнять действия с курсором, например:
cur.hasNext() - проверяет, есть ли следующий элемент и возвращает true/false
cur.next() - возвращает текущий элемент и передвигает курсор на одно значение вперед.
cur.limit(5) - лимит на количество выводимых документов
cur.sort({name:-1}) - сортировка по name полю, по возрастанию
cur.sort({name:-1}).limit(3) - сортировка + лимит
cur.sort({name:-1}).limit(3).skip(2) - сортировка +лимит, вывод начиная с 3 документа
Recall the documents in the scores collection: db.scores.find({type: "exam"}).sort({score:-1}).skip(50).limit(20)
Подсчет результатов: Для подсчета результатов будем использовать функцию count, синтаксис схож с синтаксисом find. То есть: db.scores.count({type:"exam"}) Функция вернет количество документов, имеющих поле exam. How would you count the documents in the scores collection where the type was "essay" and the score was greater than 90? db.scores.count({type:"essay",score:{$gt:90}})
Обновление документов: Заменить документ в монго можно с помощью функции update: db.collection.update({name:"Tim"},{score:200}) Заменяет документ с именем Tim на документ name:Tim, score:200, удаляя предыдущий.
Let's say you had a collection with the following document in it:
Для того, чтобы просто обновить документ, а именно обновить значение какого либо поля нужно написать следующее: db.collection.update({name:"Tim"},{$set:{score:200}}) Если нам нужно прибавить к нашему score, например, единицу: db.collection.update({name:"Tim"},{$inc:{score:1}}) Если поле score не создано в документе, то оно создается и будет равно единице. For the users collection, the documents are of the form
Hint: You should not need to pass the "phone" field to the update query. db.users.update({"_id":"myrnarackham"},{$set:{country: "RU"}})
Удаление поля:Иногда нам приходиться удалять какие либо поля из документа, для этого существует $unset: db.people.update({name:"Jones"},{$unset:{profession:1}}) - удаляем из документа с именем Jones поле profession. Write an update query that will remove the "interests" field in the following document in the userscollection.
This is a fully functional web shell, so please press enter for your query to get passed to the server, just like you would for the command line shell. db.users.update({"_id":"jimmy"},{$unset:{interests:1}})
db.people.find()
Как мы знаем, с помощью этой функции выводятся все документы существующие в people коллекции. Присвоим переменной cur значение этой функции:
cur = db.people.find()
Теперь мы можем выполнять действия с курсором, например:
cur.hasNext() - проверяет, есть ли следующий элемент и возвращает true/false
cur.next() - возвращает текущий элемент и передвигает курсор на одно значение вперед.
cur.limit(5) - лимит на количество выводимых документов
cur.sort({name:-1}) - сортировка по name полю, по возрастанию
cur.sort({name:-1}).limit(3) - сортировка + лимит
cur.sort({name:-1}).limit(3).skip(2) - сортировка +лимит, вывод начиная с 3 документа
Quiz: Querying, Cursors
{
"_id" : ObjectId("50844162cb4cf4564b4694f8"),
"student" : 0,
"type" : "exam",
"score" : 75
}
Write a query that retrieves exam documents, sorted by score in descending order, skipping the first 50 and showing only the next 20.Quiz: Counting Results
Quiz: Wholesale Updating of a Document
{ "_id" : "Texas", "population" : 2500000, "land_locked" : 1 }
and you issued the query:db.foo.update({_id:"Texas"},{population:30000000})
What would be the state of the collection after the update?
Quiz:
{
"_id" : "myrnarackham",
"phone" : "301-512-7434",
"country" : "US"
}
Please set myrnarackham's country code to "RU" but leave the rest of the document (and the rest of the collection) unchanged. Hint: You should not need to pass the "phone" field to the update query.
Quiz:
{
"_id" : "jimmy" ,
"favorite_color" : "blue" ,
"interests" : [ "debating" , "politics" ]
}
Do not simply empty the array. Remove the key : value pair from the document. This is a fully functional web shell, so please press enter for your query to get passed to the server, just like you would for the command line shell.
Комментариев нет:
Отправить комментарий