Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
How to return only a single property “_id” in MongoDB?
Following is the syntax to return only a single property _id in MongoDB
db.yourCollectionName.find({}, {"_id": 1}).pretty();
Let us first create a collection with documents
> db.singlePropertyIdDemo.insertOne({"_id":101,"UserName":"Larry","UserAge":21});
{ "acknowledged" : true, "insertedId" : 101 }
> db.singlePropertyIdDemo.insertOne({"_id":102,"UserName":"Mike","UserAge":26});
{ "acknowledged" : true, "insertedId" : 102 }
> db.singlePropertyIdDemo.insertOne({"_id":103,"UserName":"Chris","UserAge":24});
{ "acknowledged" : true, "insertedId" : 103 }
> db.singlePropertyIdDemo.insertOne({"_id":104,"UserName":"Robert","UserAge":23});
{ "acknowledged" : true, "insertedId" : 104 }
> db.singlePropertyIdDemo.insertOne({"_id":105,"UserName":"John","UserAge":27});
{ "acknowledged" : true, "insertedId" : 105 }
Following is the query to display all documents from a collection with the help of find() method
> db.singlePropertyIdDemo.find().pretty();
This will produce the following output
{ "_id" : 101, "UserName" : "Larry", "UserAge" : 21 }
{ "_id" : 102, "UserName" : "Mike", "UserAge" : 26 }
{ "_id" : 103, "UserName" : "Chris", "UserAge" : 24 }
{ "_id" : 104, "UserName" : "Robert", "UserAge" : 23 }
{ "_id" : 105, "UserName" : "John", "UserAge" : 27 }
Following is the query to return only a single property _id
> db.singlePropertyIdDemo.find({}, {"_id": 1}).pretty();
This will produce the following output
{ "_id" : 101 }
{ "_id" : 102 }
{ "_id" : 103 }
{ "_id" : 104 }
{ "_id" : 105 } Advertisements
