mongodb

17
五月
2021

mongodb(2019/9/3)

控制台操作

启动

mongo

切换数据库

use foobar

查看当前数据库

db

插入

post = {  
title : "My Blog Post",  
content : "Here's my blog post",  
date : new Date()  
}  
db.blog.insert(post)

查找

db.blog.find()  
db.blog.findOne()  
db.blog.findOne({"title" : "My Blog Post"})

更新

post.comments = []  
db.blog.update({"title" : "My Blog Post"}, post)

删除

db.blog.remove({"title":"My Blog Post"})

显示所有数据库

show dbs

显示当前数据库所有集合

show collections

帮助

help

退出

exit

python操作

导入

import pymongo

连接服务器

myclient = pymongo.MongoClient('mongodb://localhost:27017/')

获取指定数据库

mydb = myclient['runoob']

获取所有数据库集合

collist = mydb.list_collection_names()  
for name in collist:  
    print(name)

添加数据

mydb = myclient["runoobdb"]  
mycol = mydb["sites"]  
mydict = { "name": "RUNOOB", "alexa": "10000", "url": "https://www.runoob.com" }  
result = mycol.insert_one(mydict)

插入多个集合

mylist = [  
  { "name": "Taobao", "alexa": "100", "url": "https://www.taobao.com"  
  { "name": "QQ", "alexa": "101", "url": "https://www.qq.com" },  
  { "name": "Facebook", "alexa": "10", "url": "https://www.facebook.com" },  
  { "name": "知乎", "alexa": "103", "url": "https://www.zhihu.com" },  
  { "name": "Github", "alexa": "109", "url": "https://www.github.com" }  
]  
result = mycol.insert_many(mylist)  

插入指定id

mylist = [
  { "_id": 1, "name": "RUNOOB", "cn_name": "菜鸟教程"},
  { "_id": 2, "name": "Google", "address": "Google 搜索"},
  { "_id": 3, "name": "Facebook", "address": "脸书"},
  { "_id": 4, "name": "Taobao", "address": "淘宝"},
  { "_id": 5, "name": "Zhihu", "address": "知乎"}
]
x = mycol.insert_many(mylist)

查询一条数据

result = mycol.find_one()

查询集合中所有数据

for x in mycol.find():  
    print(x)

查询指定字段的数据

for x in mycol.find({},{ "_id": 0, "name": 1, "alexa": 1 }):  
    print(x)

根据指定条件查询

myquery = { "name": "RUNOOB" }  
mydoc = mycol.find(myquery)  
for x in mydoc:  
    print(x)

修改数据

myquery = { "alexa": "10000" }  
newvalues = { "$set": { "alexa": "12345" } }  
mycol.update_one(myquery, newvalues)

myquery = { "name": { "$regex": "^F" } }  
newvalues = { "$set": { "alexa": "123" } }  
x = mycol.update_many(myquery, newvalues)

排序(升序)

mydoc = mycol.find().sort("alexa")

排序(降序)

mydoc = mycol.find().sort("alexa", -1)

删除数据

myquery = { "name": "Taobao" }  
mycol.delete_one(myquery)

删除文档

myquery = { "name": {"$regex": "^F"} }  
x = mycol.delete_many(myquery)

删除集合

mycol = mydb["sites"]  
mycol.drop()
TAG

网友评论

共有访客发表了评论
请登录后再发布评论,和谐社会,请文明发言,谢谢合作! 立即登录 注册会员