As you know MongoDB in no SQL database. MongoDB noSQL makes it faster than relational database. MongoDB based on documents. Document can be any valid json object. This json object can have nested structure. This article illustrates searching mechanism with MongoDB.
Lets have some proper json document
{
"name": "testUser",
"deviceId": "android",
"type": "contract",
"address": "D14/150 London"
}
{
"name": "testUser2",
"deviceId": "android",
"type": "contract",
"address": "D14/150 London"
}
{
"name": "testUser3",
"deviceId": "android",
"type": "contract",
"address": "D14/150 London"
}
Insert documents like below using MongoDB shell
> db.analytics.insertOne({ "name": "testUser", "deviceId": "android", "type": "contract", "address": "D14/150 London" });
{
"acknowledged" : true,
"insertedId" : ObjectId("5e0dc9a3e6ebcea82c40836c")
}
Let's find documents where name is equal to testUser
> db.analytics.find({name:"testUser"}).pretty();
{
"_id" : ObjectId("5e0dc9a3e6ebcea82c40836c"),
"name" : "testUser",
"deviceId" : "android",
"type" : "contract",
"address" : "D14/150 London"
}
Lets find documents where name is testUser and type is contract
> db.analytics.find({name:"testUser", type: "contract"}).pretty();
{
"_id" : ObjectId("5e0dc9a3e6ebcea82c40836c"),
"name" : "testUser",
"deviceId" : "android",
"type" : "contract",
"address" : "D14/150 London"
}
Search in MongoDB in nested documents. Let's create some nested documents
{
"name": "newUser",
"deviceId": "android",
"type": "full",
"address": "D14/150 London",
"phone": {
"home": 123404,
"office": 485
}
}
{
"name": "newUser1",
"deviceId": "android",
"type": "full",
"address": "D14/150 London",
"phone": {
"home": 000,
"office": 485
}
}
Here the result of query
> db.analytics.find({"phone.home": 000}).pretty();
{
"_id" : ObjectId("5e0dccaae6ebcea82c408371"),
"name" : "newUser1",
"deviceId" : "android",
"type" : "full",
"address" : "D14/150 London",
"phone" : {
"home" : 0,
"office" : 485
}
}