What is the select query equivalent in PyMongo/MongoDB native query?
The TLDR answer:
Coming from the SQL domain, you might stumble upon requirement of writing a select <field_1>, <field_2> from xyz
in Mongodb. It might be a little tempting to not use select query, but try to avoid doing it, since it might be possible that your MongoDB collection has 100s of fields, so it might be a bit heavy on the network bandwidth. So now that we have discussed the advantages of using select query, lets see how we can use select query in MongoDB which is equivalent to any SQL query.
------------------------
// Select query with _id
SELECT id,
title,
status
FROM blog_posts;
db.blog_posts.find(
{},
{title: 1, status: 1}
)
-------------------------
// Select query without _id
SELECT title, status
FROM blog_posts
db.blog_posts.find(
{ },
{ title: 1, status: 1, _id: 0 }
)
--------------------------
// Select query with filter
SELECT title, status
FROM blog_posts
WHERE status = "A"
db.blog_posts.find(
{ status: "A" },
{ title: 1, status: 1, _id: 0 }
)
--------------------------
By default MongoDB would be always sending the _id
field, so you have to manually set it to false. In a nutshell we have to pass a new dict with all the fields which we want to select.
db.<collection>.find({<query>, {<select fields>}}
Until now we have seen all the simple cases, now how can we select nested fields? Dah!! Isn't MonoDB so great since we don't have to follow any schema, but with great power comes great responsibilities. What if I try to select fields which are in nested field and also what if few of the fields are not having values, how to handle that?
db.blog_posts.find(
{ details.body: {"$exists": True },
{ title: 1, details.body.raw_content: 1, status: 1, _id: 0 }
)
First make sure that the parent object exists, if the parent object exists then select the nested data inside the document.
The same query structure would be useful while using PyMongo. You might only need to change the syntax a bit as per the requirements.