python的mongo模块

本文介绍了一个使用Python与MongoDB进行数据交互的例子,演示了如何插入一条包含标题、内容和作者信息的记录,并展示了如何查询特定作者的文章。

vi an_mongo.py

#!/usr/bin/python3
# -*- coding: utf-8- -*-

import pymongo

from pymongo import MongoClient

client = MongoClient('localhost', 27017)

db = client.pymongo_test

posts = db.posts

post_data = {
    'title': 'Python and MongoDB',
    'content': 'PyMongo is fun, you guys',
    'author': 'Scott'
}
result = posts.insert_one(post_data)
print('One post: {0}'.format(result.inserted_id))

mongo

MongoDB shell version: 2.6.12
connecting to: test
> show databases;
admin  (empty)
cvedb  0.953GB
local  0.078GB
> show databases;
admin         (empty)
cvedb         0.953GB
local         0.078GB
pymongo_test  0.078GB
> use pymongo_test
switched to db pymongo_test
> show tables;
posts
system.indexes
> db.posts.find().count()
1
> db.posts.find().pretty()
{
        "_id" : ObjectId("5a7973ed594c1009eb0a5c04"),
        "author" : "Scott",
        "content" : "PyMongo is fun, you guys",
        "title" : "Python and MongoDB"
}
> db.posts.find("author":"Scott")
2018-02-06T17:25:40.885+0800 SyntaxError: Unexpected token :
> db.posts.find('author':'Scott')
2018-02-06T17:26:25.536+0800 SyntaxError: Unexpected token :
> db.posts.find({'author':'Scott'})
{ "_id" : ObjectId("5a7973ed594c1009eb0a5c04"), "author" : "Scott", "content" : "PyMongo is fun, you guys", "title" : "Python and MongoDB" }
> 

mongo数据库是一个_id,然后跟上你的一串数据,以“,”做分割,看一个复杂一点的数据:

{ "_id" : ObjectId("5a77f788a4f2d63dbb53f84b"), "id" : "cpe:2.3:a:%240.99_kindle_books_project:%240.99_kindle_books:6:-:-:-:-:android", "title" : "$0.99 Kindle Books project $0.99 Kindle Books (aka com.kindle.books.for99) for android 6.0", "references" : [ "https://play.google.com/store/apps/details?id=com.kindle.books.for99", "https://docs.google.com/spreadsheets/d/1t5GXwjw82SyunALVJb2w0zi3FoLRIkfGPc7AMjRF0r4/edit?pli=1#gid=1053404143" ], "cpe_2_2" : "cpe:/a:%240.99_kindle_books_project:%240.99_kindle_books:6::~~~android~~" }

mongo库中的状态是:

{
        "_id" : ObjectId("5a77f788a4f2d63dbb53f84b"),
        "id" : "cpe:2.3:a:%240.99_kindle_books_project:%240.99_kindle_books:6:-:-:-:-:android",
        "title" : "$0.99 Kindle Books project $0.99 Kindle Books (aka com.kindle.books.for99) for android 6.0",
        "references" : [
                "https://play.google.com/store/apps/details?id=com.kindle.books.for99",
                "https://docs.google.com/spreadsheets/d/1t5GXwjw82SyunALVJb2w0zi3FoLRIkfGPc7AMjRF0r4/edit?pli=1#gid=1053404143"
        ],
        "cpe_2_2" : "cpe:/a:%240.99_kindle_books_project:%240.99_kindle_books:6::~~~android~~"
}

mongo刚接触2天,还不是特别熟悉。

 

转载于:https://www.cnblogs.com/zw2002/p/8423313.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值