MongoDB和MySQL对比查询
查询userName包含A的数据
MySQL: SELECT * FROM UserInfo WHERE userName LIKE "%A%";
MongoDB: db.UserInfo.find({userName :/A/})
查询以字母A开头的数据
MySQL: SELECT * FROM UserInfo WHERE userName LIKE "A%";
MongoDB: db.UserInfo.find({userName :/^A/})
查询所有数据
MySQL: SELECT * FROM UserInfo;
MongoDB: db.UserInfo.find()
查询特定列
MongoDB的_id列是默认查询出来的,不管该记录中是否存在userName,Age,Status这三个字段,userName:1就是显示该字段,userName:0就是不显示该字段,所以要不显示_id,就可以加上_id:0即可
MySQL: SELECT _id,userName,Age,Status FROM UserInfo;
MongoDB: db.UserInfo.find({},{userName:1,Age:1,Status:1})
查询Status的值为A的所有数据
MySQL: SELECT * FROM UserInfo WHERE Status ='A';
MongoDB: db.UserInfo.find({Status:"A"})
查询Status的值为A的特定字段数据
MySQL: SELECT userName FROM UserInfo WHERE Status ='A';
MongoDB: db.UserInfo.find({Status:"A"},{userName:1,_id:0})
查询Status的值不等于A的所有字段
MySQL: SELECT * FROM UserInfo WHERE Status != "A";
MongoDB: db.UserInfo.find({ Status : { $ne: "A" } })
AND条件查询,查询出同时2个或以上条件都成立的数据
MySQL: SELECT * FROM UserInfo WHERE Status = "A" AND Age = 45;
MongoDB: db.UserInfo.find({ Status : "A" ,Age:45 })
OR条件查询,查询出2个或以上条件至少一个成立的数据
MySQL: SELECT * FROM UserInfo WHERE Status = "A" OR Age = 45;
MongoDB: db.UserInfo.find({$or:[{Status : "A"} ,{Age:45}]})
大于号(>)条件查询
MySQL: SELECT * FROM UserInfo WHERE Age > 45;
MongoDB: db.UserInfo.find({Age:{$gt:45}})
小于号(<)条件查询
MySQL: SELECT * FROM UserInfo WHERE Age < 45;
MongoDB: db.UserInfo.find({Age:{$lt:45}})
查询Age值的范围在25(>)到45(<=)之间
MySQL: SELECT * FROM UserInfo WHERE Age > 25 AND Age <=45;
MongoDB: db.UserInfo.find({Age:{$gt:25,$lte:45}})
查询结果使用ORDER BY 字段 ASC排序
MySQL: SELECT * FROM UserInfo WHERE userName ="Lucy" ORDER BY _id ASC;
MongoDB: db.UserInfo.find({userName :"Lucy"}).sort({_id:1})
查询结果使用ORDER BY 字段 DESC排序
MySQL: SELECT * FROM UserInfo WHERE userName ="Lucy" ORDER BY _id DESC;
MongoDB: db.UserInfo.find({userName :"Lucy"}).sort({_id:-1}