Skip to content

Instantly share code, notes, and snippets.

@altayalp
Created August 4, 2016 12:46
Show Gist options
  • Save altayalp/a9aefb6364d3a6736e662ff270c94f11 to your computer and use it in GitHub Desktop.
Save altayalp/a9aefb6364d3a6736e662ff270c94f11 to your computer and use it in GitHub Desktop.
Migrate some queries from MySQL To MongoDB

Select database

use my_db;

Mysql: Create table. MongoDb: Create collection

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `surname` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;
// Method 1
db.users.insert({
    name: "Example name",
    surname: "Example surname"
 });

 // Method 2
 db.createCollection("users");

Mysql: Get list of all tables. MongoDb: Get list of all collections.

show tables;
show collections;

Select all fields

select * from users
db.users.find();

Select some fields

select name, surname from users
db.users.find({}, {
    "name": 1,
    "surname": 1
});

Where clause

select * from users where id=10
db.users.find({
    "id": 10
});

Order fields

select * from users order by id desc
db.users.find().sort({
    "id": -1
});

Limit Data Selections

select * from users order by id desc limit 10
db.users.find().limit(10).sort({
    "id": -1
});

Data Selections using limit and offset

select * from users order by id desc limit 10, 20
db.users.find().limit(10).skip(20).sort({
    "id": -1
});

Insert data

insert into users(name, surname) values ("Example name", "Example surname");
db.users.insert(
   { title: "Example name", text: "Example surname" }
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment