Friday, July 6, 2018

Mongodb sample queries

Assuming DB name is "master" and table(collection) name is "top"

Command line:
> use master
> db.getCollection("top").count() (or better db.top.count())
> db.getCollection("top").find({"query" : "best goa beaches"}).count();
> db.getCollection("top").find({"query" : "best goa beaches", "is_last_page": true}).count();
> db.getCollection("top").drop()
> db.places.distinct('result.place_id').length //distinct on nested field and length(not count)
> db.dm.find({ dist: { $lt: 5000 } ,type1: 'zoo', type2:'hotel'} ).count(); //less than operator
PHP:  $query_assoc = array();
$query_assoc['type1'] = 'zoo';
$query_assoc['type2'] = 'hotel';
$query_assoc['dist'] = array('$lt'=> $radius);
> db.places.find({ "result.place_id": { $in: ['ChIJYU0mP3W_vzsReXl288rhJ9M'] }},{"result.name":1} ) //find and project with "in" clause

> db.dm.find({g_dist: {$gt: 0}},{g_dist:1} ).sort({"g_dist":1}).limit(1) //find with projection and sort
Response: { "_id" : ObjectId("5b449e47a387a535a00013bb"), "g_dist" : 134 }

> db.places.find({place_type: {$exists: false}}).count() //whether the field exists?
> db.places.updateMany({eplace: 'Goa'}, {$set: {eplace: 'kk'}}) //update where


> import/export
mongodump -d <database_name> -o <directory_backup>
mongorestore -d <database_name> <directory_backup>

PHP:
$manager = new MongoDB\Driver\Manager(); //localhost
$bulk = new MongoDB\Driver\BulkWrite;
$record = array("a" => "b");
$bulk->insert($record);
$manager->executeBulkWrite('master.top', $bulk); //write  
getCount($manager, array('query' => $q, 'page' => $page));//get record count meeting the criteria


function getCount($manager, $q) {
$query = new MongoDB\Driver\Query($q);
$rows = $manager->executeQuery('master.top', $query);
$count = 0;
foreach($rows as $doc) {
++$count;
}
return $count;
}

Blog Archive