现在的位置: 首页 > 综合 > 正文

MongoDB 入门

2014年02月23日 ⁄ 综合 ⁄ 共 1874字 ⁄ 字号 评论关闭
基本操作
> use tutorial
switched to db tutorial
> db.users.insert({username: "smith"})
> db.users.find()
{ "_id" : ObjectId("52ad42948312746372d831ae"), "username" : "smith"
> db.users.save({username: "jones"})
> db.users.count()
2
> db.users.find()
{ "_id" : ObjectId("52ad42948312746372d831ae"), "username" : "smith"
{ "_id" : ObjectId("52ad42bf8312746372d831af"), "username" : "jones"
> db.users.find({username: "jones"})
{ "_id" : ObjectId("52ad42bf8312746372d831af"), "username" : "jones"
> db.users.update({username: "smith"},{$set: {country: "Canada"}})
> db.users.find({username: "smith"})
{ "_id" : ObjectId("52ad42948312746372d831ae"), "country" : "Canada", "username" : "smith" }
> db.users.update({username: "smith"},{$unset: {country: 1}})
> db.users.find({username: "smith"})
{ "_id" : ObjectId("52ad42948312746372d831ae"), "username" : "smith" }
> db.users.update( {username: "smith"},
... { $set: {favorites:
...   {
...     cities: ["Chicago","Cheyenne"],
...     movies: ["Casablanca", "The Sting"]
...   }
... }
... })
> db.users.update( {username: "jones"},
...  { "$set": {favorites:
...     {
...       movies: ["Casablanca", "Rocky"]
...     }
...  }
... })
> db.users.find()
{ "_id" : ObjectId("52ad42948312746372d831ae"), "favorites" : { "cities" : [  "Chicago",  "Cheyenne" ], "movies" : [  "Casablanca",  "The Stin
g" ] }, "username" : "smith" }
{ "_id" : ObjectId("52ad42bf8312746372d831af"), "favorites" : { "movies" : [  "Casablanca",  "Rocky" ] }, "username" : "jones" }
> db.users.find({"favorites.movies": "Casablanca"})
{ "_id" : ObjectId("52ad42948312746372d831ae"), "favorites" : { "cities" : [  "Chicago",  "Cheyenne" ], "movies" : [  "Casablanca",  "The Stin
g" ] }, "username" : "smith" }
{ "_id" : ObjectId("52ad42bf8312746372d831af"), "favorites" : { "movies" : [  "Casablanca",  "Rocky" ] }, "username" : "jones" }
>

连接数据库

import sys

from pymongo import Connection
from pymongo.errors import ConnectionFailure

def main():
    try:
        c=Connection(host="localhost",port=27017)
        print "Connection successfully"
    except ConnectionFailure,e:
        sys.stderr.write("Could not connect to the MongoDB: %s" % e)
        sys.exit(1)
if __name__ == "__main__":
    main()

抱歉!评论已关闭.