понедельник, 3 февраля 2014 г.

CRUD operation. 4 часть, надеюсь последняя.

Эту часть начнем с операциями над массивом, для начала создадим документ:
db.array.insert({_id:0, a:[1,2,3,4]})
Для изменения элемента используем функцию:
db.array.update({_id:0},{$set:{"a.2":5}})
после использования функции db.array.findOne():
{_id:0, a:[1,2,5,4]}
Для добавления нового элемента:
db.array.update({_id:0},{$push:{a:5}})
findOne: {_id:0, a:[1,2,5,4,6]}
Удаление элемента с конца:
db.array.update({_id:0},{$pop:{a:1}})
findOne: {_id:0, a:[1,2,5,4]}
Удаление элемента с начала:
db.array.update({_id:0},{$pop:{a:-1}})
findOne: {_id:0, a:[2,5,4]}
Добавление нескольких элементов в конец:
db.array.update({_id:0},{$pushAll:[7,8,9]})
findOne: {_id:0, a:[2,5,4,7,8,9]}
Удаление конкретного значения из массива:
db.array.update({_id:0},{$pull:5})
findOne: {_id:0, a:[2,4,7,8,9]}
Удаление нескольких элементов:
db.array.update({_id:0},{$pullAll:{a:[2,4,8]})
findOne: {_id:0, a:[7,9]}
Добавление в конец:
db.array.update({_id:0},{$addToSet{a:5})
findOne: {_id:0, a:[7,9,5]}
При повторе последнего действия несколько раз ничего не произойдет, добавляет значение только единожды!


Quiz: Using $push, $pop, $pull, $pushAll, $pullAll, $addToSet

Suppose you have the following document in your friends collection:
{ _id : "Mike", interests : [ "chess", "botany" ] }
What will the result of the following updates be?
db.friends.update( { _id : "Mike" }, { $push : { interests : "skydiving" } } );
db.friends.update( { _id : "Mike" }, { $pop : { interests : -1 } } );
db.friends.update( { _id : "Mike" }, { $addToSet : { interests : "skydiving" } } );
db.friends.update( { _id : "Mike" }, { $pushAll: { interests : [ "skydiving" , "skiing" ] } } );
{ _id : "Mike", interests : [ "botany","skydiving","skydiving" , "skiing" ] }
Upserts:
Если в коллекции отсутствует документ с именем, например, George, то следующая операция ничего не изменит в коллекции:
db.people.update({name : "George"},{$set:{age:40}})
Для того, чтобы произошло добавление в коллекцию, в случае отсутствия документа нам нужно следующее:
db.people.update({name : "George"},{$set:{age:40}},{upserts:true})
Еще пример, после такой команды и, с условием, если в коллекции отсутствует док-ты с таким условием: 
db.people update({age:{$gt:50}},{$set:{name:"William"}},{upsert:true})
создастся новый документ с name : William.

Quiz: Upserts

After performing the following update on an empty collection
db.foo.update({username:'bar'}, {'$set':{'interests':['cat', 'dog']}}, {upsert: true} );
What could be the state of the collection.
Multi-update:
Для изменения нескольких документов можно использовать  multi:true, например:
db.people.update({},{$set:{title:"Dr"}},{multi:true})
В каждый документ people коллекции добавиться поле title со значением "Dr".

Quiz: Multi-update

Recall the schema of the scores collection:
{
 "_id" : ObjectId("50844162cb4cf4564b4694f8"),
 "student" : 0,
 "type" : "exam",
 "score" : 75
}
Give every document with a score less than 70 an extra 20 points. 

If you input an incorrect query, don't forget to reset the problem state, as any wrong update will likely take you away from your initial state.
> db.scores.update({score:{$lt:70}},{$inc:{score:20}},{multi:true})

Удаление:
Удаление имеет такой же синтаксис как и find(), а чтобы удалить все документы из коллекции достаточно написать:
db.people.remove() 
или
db.people.drop()

Quiz: Remove

Recall the schema of the scores collection:
{
 "_id" : ObjectId("50844162cb4cf4564b4694f8"),
 "student" : 0,
 "type" : "exam",
 "score" : 75
}
Delete every document with a score of less than 60.
 > db.scores.remove({score:{$lt:60}})


Комментариев нет:

Отправить комментарий