How to select fields in mongodb query?

Member

by gilbert , in category: PHP Databases , 9 months ago

How to select fields in mongodb query?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , 3 months ago

@gilbert 

To select specific fields in a MongoDB query, you can use the projection parameter of the find() method. The projection parameter takes a document that specifies the fields you want to include or exclude in the returned documents.


For example, suppose you have a collection called users with documents that have the following structure:

1
2
3
4
5
6
{
  _id: 1,
  name: "John",
  age: 30,
  email: "john@example.com"
}


To return only the name and age fields for all documents in the users collection, you can use the following query:

1
db.users.find({}, { name: 1, age: 1 })


The first argument to find() is the filter document, which specifies the selection criteria for the query. In this case, we are not applying any filters and want to return all documents in the collection, so we pass an empty filter document {}.


The second argument is the projection document, which specifies the fields we want to include in the returned documents. In this case, we are using the projection document { name: 1, age: 1 }, which specifies that we want to include the name and age fields and exclude all other fields.


By default, MongoDB includes all fields in the returned documents. To exclude specific fields, you can use the projection document to specify the fields you want to exclude. For example, to exclude the email field, you can use the following projection document:

1
{ email: 0 }


You can also use the 0 and 1 notation to mix inclusion and exclusion in the same projection. For example, to include the name and age fields and exclude the email field, you can use the following projection document:

1
{ name: 1, age: 1, email: 0 }


Note that the projection document is optional. If you do not specify a projection document, MongoDB will include all fields in the returned documents.