MongoDB快速开始(V6.0)

1. 切换数据库

显示当前数据库

db

切换数据库

use examples

2. 插入文档

MongoDB stores documents in collections. Collections are analogous to tables in relational databases. If a collection does not exist, MongoDB creates the collection when you first store data for that collection.

db.movies.insertMany([
   {
      title: 'Titanic',
      year: 1997,
      genres: [ 'Drama', 'Romance' ],
      rated: 'PG-13',
      languages: [ 'English', 'French', 'German', 'Swedish', 'Italian', 'Russian' ],
      released: ISODate("1997-12-19T00:00:00.000Z"),
      awards: {
         wins: 127,
         nominations: 63,
         text: 'Won 11 Oscars. Another 116 wins & 63 nominations.'
      },
      cast: [ 'Leonardo DiCaprio', 'Kate Winslet', 'Billy Zane', 'Kathy Bates' ],
      directors: [ 'James Cameron' ]
   },
   {
      title: 'The Dark Knight',
      year: 2008,
      genres: [ 'Action', 'Crime', 'Drama' ],
      rated: 'PG-13',
      languages: [ 'English', 'Mandarin' ],
      released: ISODate("2008-07-18T00:00:00.000Z"),
      awards: {
         wins: 144,
         nominations: 106,
         text: 'Won 2 Oscars. Another 142 wins & 106 nominations.'
      },
      cast: [ 'Christian Bale', 'Heath Ledger', 'Aaron Eckhart', 'Michael Caine' ],
      directors: [ 'Christopher Nolan' ]
   }
])

3. 查询所有文档

To select the documents from a collection, you can use the db.collection.find() method. To select all documents in the collection, pass an empty document as the query filter document to the method.

db.movies.find( { } )

4. 过滤数据

查找导演为“Christopher Nolan”的文档

db.movies.find( { "directors": "Christopher Nolan" } );

查找2000年前上映的文档

db.movies.find( { "released": { $lt: ISODate("2000-01-01") } } );

查找获奖数目超过一百的文档

db.movies.find( { "awards.wins": { $gt: 100 } } );

查找语言为中文或者日语的电影文档

db.movies.find( { "languages": { $in: [ "Japanese", "Mandarin" ] } } )

5. 投影字段(Project Field)

查询文档,只返回标题、导演和年份字段

db.movies.find( { }, { "title": 1, "directors": 1, "year": 1 } );

查询文档,返回标题和分类字段,忽略id字段

db.movies.find( { }, { "_id": 0, "title": 1, "genres": 1 } );

6. 聚合查询

While find() operations are useful for data retrieval, the aggregation pipeline allows you to manipulate data, perform calculations, and write more expressive queries than simple CRUD operations.

统计所有电影类型的的数量

db.movies.aggregate( [
   { $unwind: "$genres" },
   {
     $group: {
       _id: "$genres",
       genreCount: { $count: { } }
     }
   },
   { $sort: { "genreCount": -1 } }
] )
posted @ 2022-11-19 01:07  llazycat  阅读(122)  评论(0)    收藏  举报