SQL语句和mongodb语法对比(一)

SQL 查询语句 MongoDB find() 语句
SELECT *FROM users db.users.find()
SELECT id,       user_id,       statusFROM users db.users.find(    { },    { user_id: 1, status: 1 })
SELECT user_id, statusFROM users db.users.find(    { },    { user_id: 1, status: 1, _id: 0 })
SELECT *FROM usersWHERE status = “A” db.users.find(    { status: “A” })
SELECT user_id, statusFROM usersWHERE status = “A” db.users.find(    { status: “A” },    { user_id: 1, status: 1, _id: 0 })
SELECT *FROM usersWHERE status != “A” db.users.find(    { status: { $ne: “A” } })
SELECT *FROM usersWHERE status = “A”AND age = 50 db.users.find(    { status: “A”,      age: 50 })
SELECT *FROM usersWHERE status = “A”OR age = 50 db.users.find(    { $or: [ { status: “A” } ,             { age: 50 } ] })
SELECT *FROM usersWHERE age > 25 db.users.find(    { age: { $gt: 25 } })
SELECT *FROM usersWHERE age < 25 db.users.find(   { age: { $lt: 25 } })
SELECT *FROM usersWHERE age > 25AND   age <= 50 db.users.find(   { age: { $gt: 25, $lte: 50 } })
SELECT *FROM usersWHERE user_id like “%bc%” db.users.find( { user_id: /bc/ } )
SELECT *FROM usersWHERE user_id like “bc%” db.users.find( { user_id: /^bc/ } )
SELECT *FROM usersWHERE status = “A”ORDER BY user_id ASC db.users.find( { status: “A” } ).sort( { user_id: 1 } )
SELECT *FROM usersWHERE status = “A”ORDER BY user_id DESC db.users.find( { status: “A” } ).sort( { user_id: -1 } )
SELECT COUNT(*)FROM users db.users.count()or

db.users.find().count()

SELECT COUNT(user_id)FROM users db.users.count( { user_id: { $exists: true } } )or

db.users.find( { user_id: { $exists: true } } ).count()

SELECT COUNT(*)FROM usersWHERE age > 30 db.users.count( { age: { $gt: 30 } } )or

db.users.find( { age: { $gt: 30 } } ).count()

SELECT DISTINCT(status)FROM users db.users.distinct( “status” )
SELECT *FROM usersLIMIT 1 db.users.findOne()or

db.users.find().limit(1)

SELECT *FROM usersLIMIT 5SKIP 10 db.users.find().limit(5).skip(10)
EXPLAIN SELECT *FROM usersWHERE status = “A” db.users.find( { status: “A” } ).explain()

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注