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
Native Querying MongoDB inside array and get the count
To query inside array and check for existence to get the count, use $exists. Let us create a collection with documents −
> db.demo296.insertOne(
... {
... "id":101,
... "Name":"Chris",
... "details":[
... {
... SubjectId:[101,103],
... "SubjectName":["MySQL","MongoDB"]
... },
... {
... SubjectId:[102,104],
... "SubjectName":["Java","C"]
... }
... ]
... }
...);
{
"acknowledged" : true,
"insertedId" : ObjectId("5e4d51715d93261e4bc9ea3b")
}
> db.demo296.insertOne(
...{
... "id":102,
... "Name":"David",
... "details":[
... {
... SubjectId:[110,113]
...
... },
... {
... SubjectId:[112,114]
...
... }
... ]
...}
...);
{
"acknowledged" : true,
"insertedId" : ObjectId("5e4d519b5d93261e4bc9ea3c")
}
> db.demo296.insertOne(
... {
... "id":103,
... "Name":"Bob",
... "details":[
... {
... "SubjectName":["C++","Python"]
... },
... {
... "SubjectName":["Spring","Hibernate"]
... }
... ]
... }
...);
{
"acknowledged" : true,
"insertedId" : ObjectId("5e4d52315d93261e4bc9ea3d")
}
Display all documents from a collection with the help of find() method −
> db.demo296.find();
This will produce the following output −
{
"_id" : ObjectId("5e4d51715d93261e4bc9ea3b"), "id" : 101, "Name" : "Chris", "details" : [
{ "SubjectId" : [ 101, 103 ], "SubjectName" : [ "MySQL", "MongoDB" ] },
{ "SubjectId" : [ 102, 104 ], "SubjectName" : [ "Java", "C" ] }
]
}
{
"_id" : ObjectId("5e4d519b5d93261e4bc9ea3c"), "id" : 102, "Name" : "David", "details" : [
{ "SubjectId" : [ 110, 113 ] }, { "SubjectId" : [ 112, 114 ] }
]
}
{
"_id" : ObjectId("5e4d52315d93261e4bc9ea3d"), "id" : 103, "Name" : "Bob", "details" : [
{ "SubjectName" : [ "C++", "Python" ] }, { "SubjectName" : [ "Spring", "Hibernate" ] }
]
}
Following is how to query MongoDB inside arrays and get the count −
> db.demo296.count( { 'details.SubjectName': {$exists: true }} );
This will produce the following output −
2
Advertisements