Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to query on list field in MongoDB?
To understand the query on list field, and/or, you can create a collection with documents.
The query to create a collection with a document is as follows −
> db.andOrDemo.insertOne({"StudentName":"Larry","StudentScore":[33,40,50,60,70]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9522d316f542d757e2b444")
}
> db.andOrDemo.insertOne({"StudentName":"Larry","StudentScore":[87,67,79,98,90]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c95230916f542d757e2b445")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.andOrDemo.find().pretty();
The following is the output −
{
"_id" : ObjectId("5c9522d316f542d757e2b444"),
"StudentName" : "Larry",
"StudentScore" : [
33,
40,
50,
60,
70
]
}
{
"_id" : ObjectId("5c95230916f542d757e2b445"),
"StudentName" : "Larry",
"StudentScore" : [
87,
67,
79,
98,
90
]
}
Here is the query on list field.
The query is as follows −
> db.andOrDemo.find({"StudentScore":70}).pretty();
The following is the output:
{
"_id" : ObjectId("5c9522d316f542d757e2b444"),
"StudentName" : "Larry",
"StudentScore" : [
33,
40,
50,
60,
70
]
}
Case 3 − Here is the query for or list field.
The query is as follows −
> db.andOrDemo.find({"$or":[ {"StudentScore":60}, {"StudentScore":90}]}).pretty();
Sample Output −
{
"_id" : ObjectId("5c9522d316f542d757e2b444"),
"StudentName" : "Larry",
"StudentScore" : [
33,
40,
50,
60,
70
]
}
{
"_id" : ObjectId("5c95230916f542d757e2b445"),
"StudentName" : "Larry",
"StudentScore" : [
87,
67,
79,
98,
90
]
}Advertisements