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
Match ID and fetch documents with $eq in MongoDB in case of array?
Use $eq operator along with find() to match ID and fetch documents. The $eq specifies equality condition. It matches documents where the value of a field equals the specified value.
Let us create a collection with documents −
> db.demo426.insert({"Ids":["110","120","101"]});
WriteResult({ "nInserted" : 1 })
> db.demo426.insert({"Ids":["100","201","401"]});
WriteResult({ "nInserted" : 1 })
> db.demo426.insert({"Ids":["501","600","700"]});
WriteResult({ "nInserted" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo426.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e75e50fbbc41e36cc3cae72"),
"Ids" : [
"110",
"120",
"101"
]
}
{
"_id" : ObjectId("5e75e51abbc41e36cc3cae73"),
"Ids" : [
"100",
"201",
"401"
]
}
{
"_id" : ObjectId("5e75e527bbc41e36cc3cae74"),
"Ids" : [
"501",
"600",
"700"
]
}
Following is the query match ID with $eq in MongoDB −
> db.demo426.find({"Ids":{$eq:"501"}});
This will produce the following output −
{ "_id" : ObjectId("5e75e527bbc41e36cc3cae74"), "Ids" : [ "501", "600", "700" ] }Advertisements