programing

삽입 후 PyMongo에서 객체 ID를 얻는 방법은 무엇입니까?

golfzon 2023. 4. 29. 10:07
반응형

삽입 후 PyMongo에서 객체 ID를 얻는 방법은 무엇입니까?

Mongo에 간단한 삽입을 하는 중입니다.

db.notes.insert({ title: "title", details: "note details"})

노트 문서가 삽입된 후, 나는 즉시 객체 ID를 받아야 합니다.삽입에서 반환되는 결과는 연결 및 오류와 관련된 기본 정보를 가지고 있지만 문서 및 필드 정보는 가지고 있지 않습니다.

upsert=true에서 update(업데이트) 기능을 사용하는 것에 대한 몇 가지 정보를 찾았습니다. 그것이 올바른 방법인지 확신할 수 없습니다. 아직 시도하지 않았습니다.

MongoDB의 멋진 점 중 하나는 ID가 클라이언트 측에서 생성된다는 것입니다.

즉, 서버에 ID가 무엇인지 묻지 않아도 됩니다. 저장할 항목을 먼저 알려주셨기 때문입니다.pymongo를 사용하면 삽입물의 반환 값이 객체 ID가 됩니다.확인해 보십시오.

>>> import pymongo
>>> collection = pymongo.Connection()['test']['tyler']
>>> _id = collection.insert({"name": "tyler"})
>>> print _id.inserted_id 
4f0b2f55096f7622f6000000

타일러의 대답은 저에게 통하지 않습니다._id.inserted_id를 사용하면 작동합니다.

>>> import pymongo
>>> collection = pymongo.Connection()['test']['tyler']
>>> _id = collection.insert({"name": "tyler"})
>>> print(_id)
<pymongo.results.InsertOneResult object at 0x0A7EABCD>
>>> print(_id.inserted_id)
5acf02400000000968ba447f

insert() 대신 insert_one() 또는 insert_many()를 사용하는 것이 좋습니다.그 두 가지는 새로운 버전을 위한 것입니다.inserted_id를 사용하여 ID를 가져올 수 있습니다.

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
myDB = myclient["myDB"]
userTable = myDB["Users"]
userDict={"name": "tyler"}

_id = userTable.insert_one(userDict).inserted_id
print(_id)

또는

result = userTable.insert_one(userDict)
print(result.inserted_id)
print(result.acknowledged)

insert()를 사용해야 할 경우 아래 줄과 같이 작성해야 합니다.

_id = userTable.insert(userDict)
print(_id)

최신 PyMongo 버전이 평가 절하됨insert대신에insert_one또는insert_many사용해야 합니다.이 함수는 다음을 반환합니다.pymongo.results.InsertOneResult또는pymongo.results.InsertManyResult물건.

이러한 개체를 사용하여.inserted_id그리고..inserted_ids속성을 입력하여 삽입된 개체 ID를 가져옵니다.

자세한 내용은 이 링크를 참조하십시오.insert_one그리고.insert_many자세한 내용은 이 링크를 참조하십시오.pymongo.results.InsertOneResult.

업데이트됨, 이전 버전이 올바르지 않아 제거됨

로도 할 수 있을 것 같습니다.db.notes.save(...)삽입을 수행한 후 _id를 반환합니다.

자세한 내용은 http://api.mongodb.org/python/current/api/pymongo/collection.html 을 참조하십시오.

some_var = db.notes.insert({ title: "title", details: "note details"})
print(some_var.inserted_id)

다음 변수에 할당하기만 하면 됩니다.

someVar = db.notes.insert({ title: "title", details: "note details"})

Python에서 Insert 뒤에 있는 ID를 가져오려면 다음과 같이 하십시오.

doc = db.notes.insert({ title: "title", details: "note details"})
return str(doc.inserted_id) # This is to convert the ObjectID (type of doc.inserted_id into string)

언급URL : https://stackoverflow.com/questions/8783753/how-to-get-the-object-id-in-pymongo-after-an-insert

반응형