从本地往mongodb导入json数据

在shell中输入
mongoimport –db test –collection restaurants –drop –file ~/downloads/primer-dataset.json

python连接实例

client = MongoClient(“mongodb://mongodb0.example.net:27017”)

选定数据库有两种方法

db = client.primer
db = client[‘primer’]

连接集合也有两种方法

coll = db.dataset
coll = db[‘dataset’]

查询

cursor = db.restaurants.find()
for document in cursor:
    print(document)
cursor = db.restaurants.find({"borough": "Manhattan"})
cursor = db.restaurants.find({"address.zipcode": "10075"})
cursor = db.restaurants.find({"grades.grade": "B"})
cursor = db.restaurants.find({"grades.score": {"$gt": 30}})
cursor = db.restaurants.find({“cuisine”: “Italian”, “address.zipcode”: “10075”
cursor = db.restaurants.find(
    {“$or”: [{“cuisine”: “Italian”}, {“address.zipcode”: “10075”}]})

排序

cursor = db.restaurants.find().sort([
    ("borough", pymongo.ASCENDING),
    ("address.zipcode", pymongo.ASCENDING)
])

修改数据

result = db.restaurants.update_one(
    {"name": "Juni"},
    {
        "$set": {
            "cuisine": "American (New)"
        },
        "$currentDate": {"lastModified": True}
    }
)
result.matched_count
result.modified_count
result = db.restaurants.update_one(
    {"restaurant_id": "41156888"},
    {"$set": {"address.street": "East 31st Street"}}
)
result = db.restaurants.update_many(
    {"address.zipcode": "10016", "cuisine": "Other"},
    {
        "$set": {"cuisine": "Category To Be Determined"},
        "$currentDate": {"lastModified": True}
    }
)

替代文档

result = db.restaurants.replace_one(
{“restaurant_id”: “41704620”},
{
“name”: “Vella 2”,
“address”: {
“coord”: [-73.9557413, 40.7720266],
“building”: “1480”,
“street”: “2 Avenue”,
“zipcode”: “10075”
}
}
)

删除数据

result = db.restaurants.delete_many({"borough": "Manhattan"})
result = db.restaurants.delete_many({})
db.restaurants.drop()
分类: 数据库

0 条评论

发表回复

Avatar placeholder

您的电子邮箱地址不会被公开。