mongo資料的操作

2021-09-26 23:55:27 字數 2179 閱讀 1347

import pymongo

from pymongo import mongoclient

client = mongoclient(

'localhost'

,27017

)db = client.haha # 建立乙個資料庫、或者連線資料庫

posts = db.posts # 建立乙個collections/或者連線collections

# 列印資料庫中所有的collection(集合)

print

(db.collection_names(include_system_collections=

false))

# 參考資料

import datetime

post =

#向collection中插入資料

post_id = posts.insert_one(post)

.inserted_id

print

(post_id)

插入多條資料

student1 =

student2 =

#查詢一條資料

data = posts.find_one(

)pprint(data)

#條件查詢

i= posts.find_one(

)pprint(i)

#空查詢

p = posts.find_one(

)pprint(p)

# 返回none

#根據id查詢

a = posts.find_one(

)print

(a)student =

collection = db.collection

# result = collection.insert(student)

# print(result)

#result = collection.insert(

[student1, student2]

)print

(result)

data = collection.find(

)for f in data:

print

(f)student =

result = collection.insert_one(student)

print

(result)

print

(result.inserted_id)

student1 =

student2 =

#result = collection.insert_many(

[student1, student2]

)print

(result)

print

(result.inserted_ids)

result = collection.find(

)print

(type

(result)

)print

(result)

for i in result:

print

(i)from bson.objectid import objectid

result = collection.find_one(

)print

(result)

results = collection.find(

).sort(

'name'

, pymongo.ascending)

# pymongo.ascending指定公升序 #pymongo.descending 表示降序

print

([result[

'name'

]for result in results]

)# condition =

# student = collection.find_one(condition)

# print(student)

# student['age'] = 25

# result = collection.update(condition, student)

# print(result)

result = collection.remove(

)print

(result)

關於mongo的操作

總結mongodb是乙個介於關聯式資料庫和非關聯式資料庫之間的產品,是非關聯式資料庫當中功能最豐富,最像關聯式資料庫的。它支援的資料結構非常鬆散,是類似json的bson格式,可以存放文字型資料。如下 示例 collection 為集合的名稱類似於mysql 的表名稱 db.collection.f...

PHP操作mongo資料庫

conn new mongoclient mongodb localhost 27017 mongodb username password host port db conn chili 選擇資料庫 col db test 選擇集合 dbs conn listdbs 檢視所有的表 collecti...

Mongo資料庫操作(三)

開通黃鑽 建立資料庫 use 如何什麼都不幹的話 會被刪除 檢視所有的資料 show dbs 給指定資料庫中新增資料 db.persons.insert 查詢資料庫中所有文件 show collections 查詢指定文件的資料 db.documentname find 查詢第一條資料 db.doc...