MongoDB read operation findOne() and find()
Read operation in mongoDB is reading or fetching data from mongoDB database , for this we have to methods .
findOne()
db.collectionName.findOne();
db.collectionName.findOne({name:'john'});
findOne() method without any filter returns the first document from the collection.
findOne({name:'john'}) returns the first matched document from the collection where name is john.
Data
[
{
name:'alex',
hobby:[
{
title:'sports',
active:2
},
{
title:'coding',
active:3
}
]
},
{
name:'john',
hobby:[
{
title:'sports',
active:2
},
{
title:'work',
active:3
}
]
}
]
Query
db.collectionName.findOne({name:'john'})
Output
{
name:'john',
hobby:[
{
title:'sports',
active:2
},
{
title:'work',
active:3
}
]
}
find()
db.collectionName.find()
db.collectionName.find({place:'bangalore'})
find() returns the all the document from the collection , it returns a cursor , means if you have 2000 or more document in the collection , find() method will not return all the document it will return 20 in the shell.
find({place:'bangalore'}) find() with filter returns all the documents from the collection after filtering it.
Data
[
{
name:'alex',
place:'bangalore',
hobby:[
{
title:'sports',
active:2
},
{
title:'coding',
active:3
}
]
},
{
name:'john',
place:'bangalore',
hobby:[
{
title:'sports',
active:2
},
{
title:'work',
active:3
}
]
}
]
Query
db.collectionName.find({place:'bangalore'})
Output
[
{
name:'alex',
place:'bangalore',
hobby:[
{
title:'sports',
active:2
},
{
title:'coding',
active:3
}
]
},
{
name:'john',
place:'bangalore',
hobby:[
{
title:'sports',
active:2
},
{
title:'work',
active:3
}
]
}
]