How to select data in mongo DB collection by Object Id.
Link to MongoDB
Mongo DB default port is 27017.
Python codes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
from pymongo import MongoClient from bson.objectid import ObjectId client = MongoClient('mongodb://ip:27017/') // Get DB list dbs = client.list_database_names() // Check if my database exists if 'myDB' in dbs: mydb = client['PlmProjects'] cols = mydb.list_collection_names() if 'ADMIN_RECORD' in cols: mycol = mydb['ADMIN_RECORD'] data = mycol.find() data_dumps = dumps(data) data_dumps_rmOID = remove_oid(data_dumps) result["result"] = 1 result["data"] = json.loads(data_dumps_rmOID) thing = mydb.ADMIN_RECORD.find_one({'_id': ObjectId('61c42aeb02009c2698896054')}) print(data_dumps) print(dumps(thing)) |
Using [DB NAME].[COLLECTION NAME].find_one({'_id': ObjectId('object id')})
to find item by object ID。
More for JSON data
from bson.json_util import dumps
import json
json decode
json.loads
Transfer JSON format into python data type.
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number(list) | int |
number(real) | float |
true | True |
false | False |
null | None |
json encode
json.dumps
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int-&float-derived Enums | number |
True | true |
False | false |
None | null |
留言