Master MongoDB Queries: Simple, Conditional, and Nested Document Searches
This tutorial walks through MongoDB query basics, showing how to perform simple retrievals, conditional filters, and nested‑document searches with clear code examples and step‑by‑step explanations for inserting and querying data.
Building on a previous article about NoSQL storage structures, this guide demonstrates MongoDB query techniques using three common patterns: simple queries, conditional queries, and nested‑document queries.
Preparing Data
First, select the target database (MongoDB creates databases and collections lazily, so no explicit creation is needed). use tutorial Insert sample documents into the users collection:
db.users.insert({username: "smith"}) db.users.save({username: "jones"})1. Simple Query
Retrieve all documents in the collection: db.users.find() Result:
{ "_id" : ObjectId("5620c919f1"), "username" : "smith" } { "_id" : ObjectId("562cececf5"), "username" : "jones" }2. Conditional Query
Find documents that match a specific condition, e.g., username equals "jones": db.users.find({username:"jones"}) Result:
{ "_id" : ObjectId("5628cececf5"), "username" : "jones" }3. Nested Document Query
First, add a nested favorites field with a movies array to the smith document:
db.users.update({username:"smith"}, {$set:{favorites:{movies:["spring","love"]}}})View the updated documents: db.users.find() Result includes:
{ "_id": ObjectId("56419f1"), "username": "smith", "favorites": { "movies": ["spring", "love"] } }Now query for users who like the movie "love": db.users.find({"favorites.movies":"love"}) This returns documents where the movies array contains the value "love".
The examples illustrate that MongoDB’s document‑oriented approach makes queries feel natural to programmers, with low learning overhead.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
