MONGODB QUERIES



https://resources.mongodb.com/getting-started-with-mongodb?jmp=nav&_ga=2.36342752.1725297401.1538219313-1839665246.1535649465


//show databeses/colelctions/colelction names
show dbs
use some_database
show collections
db.getCollectionNames()

//insert data to collection
db.Users.insert({"name":"tutorials point"})

db.Users.insert({
   title: 'A-MongoDB Overview2',
   description: 'MongoDB is no sql database',
   by: 'tutorials point',
   url: 'http://www.tutorialspoint.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 400,
   createdDate : new Date(2018, 12, 12, 14, 12)
})

//get colelction datas
db.Users.find();

//show distinct values
db.items.distinct("category", {})

//find ( or , and )
db.Users.find(
   {
      $and: [
         {title: 'MongoDB Overview'},
         {likes: { $gt: 50 } }
      ]
   }
).pretty()
db.Users.find(
   {
      $or: [
         {title: 'MongoDB Overview2'},
         {likes: { $lt: 50 } }
      ]
   }
).pretty().sort({likes:-1})

//update document
db.Users.update({'title':'MongoDB Overview1'},
   {$set:{'title':'New MongoDB Tutorial'}},{multi:true})
 
//limit , skip , sorting
db.Users.find({}).limit(2)
db.Users.find({},{"_id":0}).limit(1).skip(1)
db.Users.find().sort({likes:-1})
db.Users.find().sort({createdDate:-1})

//like query
db.Users.find({"title": /.*Overview2.*/})

//add index
db.Users.ensureIndex({"likes":-1})

//see exsiting indexes 
db.nums.getIndexes()

//group by - sum
db.Users.aggregate([{
                        $group : {
                            _id : "$likes",
                            Count : {$sum : 1}
                        }
                    }])
//group by - avarage
db.Users.aggregate([{$group : {_id : "$title", AvarageLikes : {$avg  : "$likes"}}}])


//where array size greather than 2
db.getCollection('Users').find({'tags.2': {$exists: true}})

//get last 5 data
db.Users.find().sort({_id:-1}).limit(5);

//get data where tags size is not 0
db.Users.find({tags: {$not: {$size: 0}}})

//where tag has mongodb
db.Users.find({tags: "mongodb"})
//where array contains
db.Users.find({tags: { $in : ["test"]} })

//between two date
db.Users.find({
    createdDate: {
        $gte:ISODate("2014-11-19T14:00:00Z"),
        $lt:ISODate("2020-11-19T14:00:00Z")
    }
})

db.createView('users_tags_not_null','Users', [{
    tags: {$not: {$size: 0}}
}])

db.users_2014_2020.find()


//JOIN TWO COLLECTION
// Show "persons along with their favorite pokemon" for persons that have one

db.persons.aggregate([
  { $lookup: {
    from: "pokemons",
    localField: "favorite_pokemon",
    foreignField: "_id",
    as: "favorite_pokemon_doc"
  }},
  { $unwind: "$favorite_pokemon_doc" }
]).pretty()

//Returns a document that contains information on in-progress operations for the database instance.
db.currentOp()

//Returns statistics that reflect the use state of a single database.
db.stats()

//copy database
db.copyDatabase('test', 'archive_test')

which of my collections are taking so the most time in queries ?
mongotop --host HOST --port PORT --username USER -p

How can I see the current number of inserts/queries etc per second
mongostat --host HOST --port PORT --username USER -p

When document was created ?
ObjectId("505bd76785ebb509fc183733").getTimestamp()



Structure of 'restaurants' collection :
{
  "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"
}
Write a MongoDB query to find the restaurants that achieved a score is more than 80 but less than 100.
db.restaurants.find({grades : { $elemMatch:{"score":{$gt : 80 , $lt :100}}}});


Write a MongoDB query to find the restaurants which locate in a latitude value less than -95.754168.
db.restaurants.find({"address.coord" : {$lt : -95.754168}});


Write a MongoDB query to find the restaurants that do not prepare any cuisine of 'American' and their grade score more than 70 and lattitude less than -65.754168.

db.restaurants.find( {$and: [ {"cuisine" : {$ne :"American "}}, {"grades.score" : {$gt : 70}}, {"address.coord" : {$lt : -65.754168}} ] } );






Write a MongoDB query to find the restaurant Id, name, borough and cuisine for those restaurants which contain 'Wil' as first three letters for its name.
db.restaurants.find( {name: /^Wil/}, { "restaurant_id" : 1, "name":1,"borough":1, "cuisine" :1 } );


Write a MongoDB query to find the restaurants which belong to the borough Bronx and prepared either American or Chinese dish.

db.restaurants.find( { "borough": "Bronx" , $or : [ { "cuisine" : "American " }, { "cuisine" : "Chinese" } ] } );



Write a MongoDB query to find the restaurant Id, name, borough and cuisine for those restaurants which achieved a score which is not more than 10.
db.restaurants.find( {"grades.score" : { $not: {$gt : 10} } }, { "restaurant_id" : 1, "name":1,"borough":1, "cuisine" :1 } );











Yorumlar

Bu blogdaki popüler yayınlar

INGILIS DILI BUTUN ZAMANLAR

İNGİLİS DİLİNDƏ ƏN ÇOX İSTİFADƏ OLUNAN 2600 CÜMLƏ QƏLİBLƏRİ VƏ 6000 SÖZ