首页 > 技术文章 > mongo

minorblog 2018-04-15 23:20 原文

Making a Connection with MongoClient

from pymongo import MongoClient
client = MongoClient()
client = MongoClient('localhost', 27017)
client = MongoClient('mongodb://localhost:27017')

Geting a Database

db = client.test_database
db = client['test-database']

Documents

import datetime
post = {
    "author":"Mike",
    "text": "My first blog post!",
    "tags": ["mongodb", "python", "pymongo"],
    "date": datetime.datetime.utcnow()
}

Inserting a Document

posts = db.posts
post_id = posts.insert_one(post).inserted_id
post_id
ObjectId('5a0aec6cb7a2272dd4be8b76')
db.collection_names(include_system_collections=False)
['posts']

Getting a Single Document With

import pprint
pprint.pprint(posts.find_one())
{'_id': ObjectId('5a0992ffb7a22723a03298c9'),
 'author': 'Mike',
 'date': datetime.datetime(2017, 11, 13, 12, 38, 53, 735000),
 'tags': ['mongodb', 'python', 'pymongo'],
 'text': 'My first blog post!'}
pprint.pprint(posts.find_one({"author":"Mike"}))
{'_id': ObjectId('5a0992ffb7a22723a03298c9'),
 'author': 'Mike',
 'date': datetime.datetime(2017, 11, 13, 12, 38, 53, 735000),
 'tags': ['mongodb', 'python', 'pymongo'],
 'text': 'My first blog post!'}
posts.find_one({"author":"Eliot"})

Querying By ObjectId

post_id
ObjectId('5a0aec6cb7a2272dd4be8b76')
pprint.pprint(posts.find_one({"_id":post_id}))
{'_id': ObjectId('5a0aec6cb7a2272dd4be8b76'),
 'author': 'Mike',
 'date': datetime.datetime(2017, 11, 14, 13, 12, 55, 379000),
 'tags': ['mongodb', 'python', 'pymongo'],
 'text': 'My first blog post!'}

推荐阅读