- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Query for values (not objects) in list with MongoDB
To query for values in list, use positional operator($) in MongoDB. Let us create a collection with documents −
> db.demo628.insertOne({id:1,Name:["Chris","David","John"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e9ae7ea6c954c74be91e6b6") } > db.demo628.insertOne({id:1,Name:["Carol","Sam"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e9ae7f26c954c74be91e6b7") } > db.demo628.insertOne({id:2,Name:["Mike","Sam","John"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e9ae8056c954c74be91e6b8") }
Display all documents from a collection with the help of find() method −
> db.demo628.find();
This will produce the following output −
{ "_id" : ObjectId("5e9ae7ea6c954c74be91e6b6"), "id" : 1, "Name" : [ "Chris", "David", "John" ] } { "_id" : ObjectId("5e9ae7f26c954c74be91e6b7"), "id" : 1, "Name" : [ "Carol", "Sam" ] } { "_id" : ObjectId("5e9ae8056c954c74be91e6b8"), "id" : 2, "Name" : [ "Mike", "Sam", "John" ] }
Query for values (not objects) in list −
> db.demo628.find({"Name":"John"}, {"id":1, "Name.$":1});
This will produce the following output −
{ "_id" : ObjectId("5e9ae7ea6c954c74be91e6b6"), "id" : 1, "Name" : [ "John" ] } { "_id" : ObjectId("5e9ae8056c954c74be91e6b8"), "id" : 2, "Name" : [ "John" ] }
Advertisements