开始之前当然要导入模块啦:
>>> import pymongo
下一步,必须本地mongodb服务器的安装和启动已经完成,才能继续下去。
建立于MongoClient 的连接:
client = MongoClient('localhost', 27017) # 或者 client = MongoClient('mongodb://localhost:27017/')
得到数据库:
>>> db = client.test_database # 或者 >>> db = client['test-database']
得到一个数据集合:
collection = db.test_collection # 或者 collection = db['test-collection']
MongoDB中的数据使用的是类似Json风格的文档:
>>> import datetime >>> post = {"author": "Mike", ... "text": "My first blog post!", ... "tags": ["mongodb", "python", "pymongo"], ... "date": datetime.datetime.utcnow()}
插入一个文档:
>>> posts = db.posts >>> post_id = posts.insert_one(post).inserted_id >>> post_id ObjectId('...')
找一条数据:
>>> posts.find_one() {u'date': datetime.datetime(...), u'text': u'My first blog post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'mongodb', u'python', u'pymongo']} >>> posts.find_one({"author": "Mike"}) {u'date': datetime.datetime(...), u'text': u'My first blog post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'mongodb', u'python', u'pymongo']} >>> posts.find_one({"author": "Eliot"}) >>>
通过ObjectId来查找:
>>> post_id ObjectId(...) >>> posts.find_one({"_id": post_id}) {u'date': datetime.datetime(...), u'text': u'My first blog post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'mongodb', u'python', u'pymongo']}
不要转化ObjectId的类型为String:
>>> post_id_as_str = str(post_id) >>> posts.find_one({"_id": post_id_as_str}) # No result >>>
如果你有一个post_id字符串,怎么办呢?
from bson.objectid import ObjectId # The web framework gets post_id from the URL and passes it as a string def get(post_id): # Convert from string to ObjectId: document = client.db.collection.find_one({'_id': ObjectId(post_id)})
多条插入:
>>> new_posts = [{"author": "Mike", ... "text": "Another post!", ... "tags": ["bulk", "insert"], ... "date": datetime.datetime(2009, 11, 12, 11, 14)}, ... {"author": "Eliot", ... "title": "MongoDB is fun", ... "text": "and pretty easy too!", ... "date": datetime.datetime(2009, 11, 10, 10, 45)}] >>> result = posts.insert_many(new_posts) >>> result.inserted_ids [ObjectId('...'), ObjectId('...')]
查找多条数据:
>>> for post in posts.find(): ... post ... {u'date': datetime.datetime(...), u'text': u'My first blog post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'mongodb', u'python', u'pymongo']} {u'date': datetime.datetime(2009, 11, 12, 11, 14), u'text': u'Another post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'bulk', u'insert']} {u'date': datetime.datetime(2009, 11, 10, 10, 45), u'text': u'and pretty easy too!', u'_id': ObjectId('...'), u'author': u'Eliot', u'title': u'MongoDB is fun'}
当然也可以约束查找条件:
>>> for post in posts.find({"author": "Mike"}): ... post ... {u'date': datetime.datetime(...), u'text': u'My first blog post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'mongodb', u'python', u'pymongo']} {u'date': datetime.datetime(2009, 11, 12, 11, 14), u'text': u'Another post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'bulk', u'insert']}
获取集合的数据条数:
>>> posts.count()
或者说满足某种查找条件的数据条数:
>>> posts.find({"author": "Mike"}).count()
范围查找,比如说时间范围:
>>> d = datetime.datetime(2009, 11, 12, 12) >>> for post in posts.find({"date": {"$lt": d}}).sort("author"): ... print post ... {u'date': datetime.datetime(2009, 11, 10, 10, 45), u'text': u'and pretty easy too!', u'_id': ObjectId('...'), u'author': u'Eliot', u'title': u'MongoDB is fun'} {u'date': datetime.datetime(2009, 11, 12, 11, 14), u'text': u'Another post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'bulk', u'insert']}
$lt是小于的意思。
如何建立索引呢?比如说下面这个查找:
>>> posts.find({"date": {"$lt": d}}).sort("author").explain()["cursor"] u'BasicCursor' >>> posts.find({"date": {"$lt": d}}).sort("author").explain()["nscanned"]
建立索引:
>>> from pymongo import ASCENDING, DESCENDING >>> posts.create_index([("date", DESCENDING), ("author", ASCENDING)]) u'date_-1_author_1' >>> posts.find({"date": {"$lt": d}}).sort("author").explain()["cursor"] u'BtreeCursor date_-1_author_1' >>> posts.find({"date": {"$lt": d}}).sort("author").explain()["nscanned"]
连接聚集
>>> account = db.Account #或 >>> account = db["Account"]
查看全部聚集名称
>>> db.collection_names()
查看聚集的一条记录
>>> db.Account.find_one() >>> db.Account.find_one({"UserName":"keyword"})
查看聚集的字段
>>> db.Account.find_one({},{"UserName":1,"Email":1}) {u'UserName': u'libing', u'_id': ObjectId('4ded95c3b7780a774a099b7c'), u'Email': u'libing@35.cn'} >>> db.Account.find_one({},{"UserName":1,"Email":1,"_id":0}) {u'UserName': u'libing', u'Email': u'libing@35.cn'}
查看聚集的多条记录
>>> for item in db.Account.find(): item >>> for item in db.Account.find({"UserName":"libing"}): item["UserName"]
查看聚集的记录统计
>>> db.Account.find().count() >>> db.Account.find({"UserName":"keyword"}).count()
聚集查询结果排序
>>> db.Account.find().sort("UserName") #默认为升序 >>> db.Account.find().sort("UserName",pymongo.ASCENDING) #升序 >>> db.Account.find().sort("UserName",pymongo.DESCENDING) #降序
聚集查询结果多列排序
>>> db.Account.find().sort([("UserName",pymongo.ASCENDING),("Email",pymongo.DESCENDING)])
添加记录
>>> db.Account.insert({"AccountID":21,"UserName":"libing"})
修改记录
>>> db.Account.update({"UserName":"libing"},{"$set":{"Email":"libing@126.com","Password":"123"}})
删除记录
>>> db.Account.remove() -- 全部删除 >>> db.Test.remove({"UserName":"keyword"})

Python은 데이터 과학, 웹 개발 및 자동화 작업에 적합한 반면 C는 시스템 프로그래밍, 게임 개발 및 임베디드 시스템에 적합합니다. Python은 단순성과 강력한 생태계로 유명하며 C는 고성능 및 기본 제어 기능으로 유명합니다.

2 시간 이내에 Python의 기본 프로그래밍 개념과 기술을 배울 수 있습니다. 1. 변수 및 데이터 유형을 배우기, 2. 마스터 제어 흐름 (조건부 명세서 및 루프), 3. 기능의 정의 및 사용을 이해하십시오. 4. 간단한 예제 및 코드 스 니펫을 통해 Python 프로그래밍을 신속하게 시작하십시오.

Python은 웹 개발, 데이터 과학, 기계 학습, 자동화 및 스크립팅 분야에서 널리 사용됩니다. 1) 웹 개발에서 Django 및 Flask 프레임 워크는 개발 프로세스를 단순화합니다. 2) 데이터 과학 및 기계 학습 분야에서 Numpy, Pandas, Scikit-Learn 및 Tensorflow 라이브러리는 강력한 지원을 제공합니다. 3) 자동화 및 스크립팅 측면에서 Python은 자동화 된 테스트 및 시스템 관리와 같은 작업에 적합합니다.

2 시간 이내에 파이썬의 기본 사항을 배울 수 있습니다. 1. 변수 및 데이터 유형을 배우십시오. 이를 통해 간단한 파이썬 프로그램 작성을 시작하는 데 도움이됩니다.

10 시간 이내에 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법은 무엇입니까? 컴퓨터 초보자에게 프로그래밍 지식을 가르치는 데 10 시간 밖에 걸리지 않는다면 무엇을 가르치기로 선택 하시겠습니까?

Fiddlerevery Where를 사용할 때 Man-in-the-Middle Reading에 Fiddlereverywhere를 사용할 때 감지되는 방법 ...

Python 3.6에 피클 파일로드 3.6 환경 보고서 오류 : modulenotfounderror : nomodulename ...

경치 좋은 스팟 댓글 분석에서 Jieba Word 세분화 문제를 해결하는 방법은 무엇입니까? 경치가 좋은 스팟 댓글 및 분석을 수행 할 때 종종 Jieba Word 세분화 도구를 사용하여 텍스트를 처리합니다 ...


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

드림위버 CS6
시각적 웹 개발 도구

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.
