Anzar
Anzar

Reputation: 35

How to get a specific field in MongoDB document

I am using PyMongo to work with MongoDB database. My aim is to get a specific field from the document. I am using "find_one" and "find" function which return the cursor not the field as such.

Here is a sample document.

{
    "_id": {
        "$oid": "622226e937a677bc5380f10f"
    },
    "name": "test user",
    "place": "test place",
    "descr": "test test test",
    "email": "[email protected]",
    "pri": "High",
    "date": "2022-03-04",
    "token": "096e9476cad5f1c59e",
    "status": "To-do"
}

What query can I use to return say "test user" in string?

Upvotes: 0

Views: 1776

Answers (1)

Pavel Bely
Pavel Bely

Reputation: 2395

Actually find_one returns single document. And you simply can get its field:

from bson.objectid import ObjectId
<..>
user = users.find_one({"_id": ObjectId("622226e937a677bc5380f10f")})
if user:
    return user["name"]

Upvotes: 1

Related Questions