воскресенье, 2 февраля 2014 г.

CRUD operation. Часть 2.

Продолжение темы CRUD в MongoDB. Постараюсь писать более форматировано)

Использование $or:
db.people.find({$or:[{name:{$regex:"e$"}},{age:{$exists:true}}]});
Происходит выборка документов, в которых поле name содержит "e" в конце строки или содержит поле age.

Quiz: Using $or

How would you find all documents in the scores collection where the score is less than 50 or greater than 90?
db.scores.find({$or:[{score:{$lt:50}},{score:{$gt:90}}]})

Использование $and:
db.people.find({$and:[{name:{$regex:"e$"}},{age:{$exists:true}}]});
Происходит выборка документов, в которых поле name содержит "e" в конце строки и присутствует поле age.

Quiz: Using $and

What will the following query do?
db.scores.find( { score : { $gt : 50 }, score : { $lt : 60 } } );
 На этот вопрос сам ответил не правильно, дело в том, что JS синтаксис считывает последние условия и применяет их, то есть score : { $lt : 60}, для того, чтобы вывелись все значения от 50 до 60 нужно ввести:
db.scores.find( { score : { $gt : 50, $lt : 60 } } );

Еще в монго есть замечательная особенность, find может искать в массивах, то есть если у нас есть 2 документа в одном из которых fruit : [ apple, banano], а во втором fruit : [ orange, banano] при запросе db.collection.find({fruit : banano}) выведет оба документа.

Quiz: Querying Inside Arrays

Which of the following documents would be returned by this query?
db.products.find( { tags : "shiny" } );
Использование $all и $in:
db.accounts.find( { favorites:{$in:["beer","ice cream" } );
Выборка документов, в которых есть хотя бы одно значение, указанное в скобках [ ], соответствующее  favorites.
db.accounts.find( { favorites:{$all:["beer","ice cream" } );
Выборка документов, в которых есть все значения, указанные в скобках [ ], соответствующее  favorites.

Quiz: Using $in and $all

Which of the following documents matches this query?
db.users.find( { friends : { $all : [ "Joe" , "Bob" ] }, favorites : { $in : [ "running" , "pickles" ] } } )
Dot notation:
Предположим, у нас существует документ {name:"Tim", email: { work: work@mail.ru, home : home@tyt.by}}, при выборке db.collection.find( {name:"Tim", email: {home : "home@tyt.by", work: "work@mail.ru"}}) или db.collection.find( {name:"Tim", email: {work: "work@mail.ru"}})  ничего не произойдет, т.к. это не массив, для таких случаев существует такой синтаксис: db.collection.find( {name:"Tim", email.work: "work@mail.ru"}).

Quiz: Queries with Dot Notation

Suppose a simple e-commerce product catalog called catalog with documents that look like this:
{ product : "Super Duper-o-phonic", 
  price : 100000000000,
  reviews : [ { user : "fred", comment : "Great!" , rating : 5 },
              { user : "tom" , comment : "I agree with Fred, somewhat!" , rating : 4 } ],
  ... }
Write a query that finds all products that cost more than 10,000 and that have a rating of 5 or better.
1
db.catalog.find({"reviews.rating" :{$gte: 5},price:{$gt:10000}})




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

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