Home > Database > MongoDB > How to sort documents and display only a single field in MongoDB 4?

How to sort documents and display only a single field in MongoDB 4?

WBOY
Release: 2023-09-01 14:41:15
forward
1453 people have browsed it

如何在 MongoDB 4 中对文档进行排序并仅显示单个字段?

To sort documents in MongoDB 4, use sort(). To display only a single sorted field, set this to 1.

Let us create a collection containing documents -

> db.demo611.insertOne({"Name":"Chris"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e987110f6b89257f5584d83")
}
> db.demo611.insertOne({"Name":"Adam"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e987115f6b89257f5584d84")
}
> db.demo611.insertOne({"Name":"John"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e987118f6b89257f5584d85")
}
> db.demo611.insertOne({"Name":"Bob"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e98711bf6b89257f5584d86")
}
Copy after login

Display all the documents in the collection with the help of find() method-

> db.demo611.find();
This will produce the following output:
{ "_id" : ObjectId("5e987110f6b89257f5584d83"), "Name" : "Chris" }
{ "_id" : ObjectId("5e987115f6b89257f5584d84"), "Name" : "Adam" }
{ "_id" : ObjectId("5e987118f6b89257f5584d85"), "Name" : "John" }
{ "_id" : ObjectId("5e98711bf6b89257f5584d86"), "Name" : "Bob" }
Copy after login

The following is how to sort the documents using MongoDB 4 The query -

> db.demo611.find().sort({Name:1});
Copy after login

will produce the following output&mius;

{ "_id" : ObjectId("5e987115f6b89257f5584d84"), "Name" : "Adam" }
{ "_id" : ObjectId("5e98711bf6b89257f5584d86"), "Name" : "Bob" }
{ "_id" : ObjectId("5e987110f6b89257f5584d83"), "Name" : "Chris" }
{ "_id" : ObjectId("5e987118f6b89257f5584d85"), "Name" : "John" }
Copy after login

The above is the detailed content of How to sort documents and display only a single field in MongoDB 4?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template