1、导出表user
mongoexport -h localhost:27017 -u username -p pwd -d 数据库名 -c user -o /home/users.json --type json -f "name,age,desc,time"
2、返回指定字段
返回item和qty不返回id
db.inventory.find( { type: 'food' }, { item: 1, qty: 1, _id:0 } )
3、插入,如果该日志(ID)已存在,则不执行(也不更新);如果不存在则插入
> db.Blog.insert({"_id":"123456", "blog_cont":"abcdef", "title":"《My Test》"})
> db.Blog.find()
{ "_id" : "123456", "blog_cont" : "abcdef", "title" : "《My Test》" }
> db.Blog.update({"_id":"123456"}, {$setOnInsert:{"blog_cont":"abc123", "other":"hello world!"}}, {upsert:true})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
>
> db.Blog.find()
{ "_id" : "123456", "blog_cont" : "abcdef", "title" : "《My Test》" }
> db.Blog.update({"_id":"123"}, {$setOnInsert:{"blog_cont":"abc123", "other":"hello world!"}}, {upsert:true})
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : "123" })
>
> db.Blog.find()
{ "_id" : "123456", "blog_cont" : "abcdef", "title" : "《My Test》"
{ "_id" : "123", "blog_cont" : "abc123", "other" : "hello world!" }
4、在3的基础上更新某个字段
> db.Blog.update({"_id":"123456"}, {$setOnInsert:{"blog_cont":"abc123", "other":"hello world!"}, $set:{"title":"《New Title》"}}, {upsert:true})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
>
> db.Blog.find()
{ "_id" : "123456", "blog_cont" : "abcdef", "title" : "《New Title》
{ "_id" : "123", "blog_cont" : "abc123", "other" : "hello world!" }
5、批量更新数据
db.getCollection('xxxx').find().forEach(
function(item){
db.getCollection('xxxx').update({"_id":item._id},{$set:{"loc": [item.lon,item.lat]}})
}
)
6、删除全表数据
db.getCollection('CollectLog').remove({})
db.getCollection('CollectLog').remove({"dateTime" : "202101070800"})
7、排序
其中 1 为升序排列,而 -1 是用于降序排列。
db.getCollection('Yj').find({"cityname" : "青岛"}).sort({'yjissuedate':-1})
8、like查询
-- SQL:
SELECT * FROM UserInfo WHERE userName LIKE "%A%"
-- MongoDB:
db.UserInfo.find({userName: /A/})
-- SQL:
SELECT * FROM UserInfo WHERE userName LIKE "A%"
--MongoDB:
db.UserInfo.find({userName :/^A/})
9、not like
select * from test where station_id_c=‘2’ and datetime not like ‘%0000’
db.test.find({"station_id_c" : "2","datetime":{"$not":/0000$/}})
10、2字段相等
db.test.find({"$where":"this.station_id_d == this.station_id_c ", "station_id_d":/^68/})