自建 MongoDB 实战 | MongoDB 文档查询

pivoteic
发布于 2023-7-10 16:08
浏览
0收藏

专题介绍:

八篇文章,近五万字。自建 MongoDB 实践系列文章,为您阐述日常工作中常用的 NoSQL 产品——MongoDB 运维相关的日常实战。主要涉及到:


· MongoDB 的安装及基本使用

  (点击进入)

· MongoDB 文档查询 (本期内容)

· MongoDB 复制集的介绍及搭建 (后续更新)

· MongoDB 分片集群的介绍及搭建 (后续更新)

· MongoDB 的备份及恢复 (后续更新)

· MongoDB 安全加密 (后续更新)

· MongoDB Change Stream 功能介绍及代码演示 (后续更新)

· MongoDB 其他(后续更新)


今日分享:《MongoDB 文档查询》

文档操作

MongoDB 中的文档操作与关系型数据中的增删改查,没什么两样,只是形式不同而已。

// 命令格式为
db.<collection name>.insert({"name":"McLeod"})

// 插入文档
> db.dogs.insert({"name": "toby"})
WriteResult({ "nInserted" : 1 })

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
test    0.000GB

> db
test

// 查看文档
db.<collection name>.find()
> db.dogs.find()
{ "_id" : ObjectId("5f3e2976f6abe840587e9679"), "name" : "toby" }

> db.cats.insert({"firstName": "coco"})
WriteResult({ "nInserted" : 1 })

> db.cats.find().pretty()
{ "_id" : ObjectId("5f3e2a06f6abe840587e967a"), "firstName" : "coco" }

// 查看集合
> show collections
cats
dogs

// 删除 db
> db.dropDatabase()
{ "dropped" : "test", "ok" : 1 }

集合操作

// 非明确创建
db.<collection name>.insert({"name":"McLeod"})

// 明确创建
db.createCollection(<name>, {<optional options>})

我们在创建集合时,还可以指定一些可选的选项。如下表所示:

自建 MongoDB 实战 | MongoDB 文档查询-鸿蒙开发者社区

一个例子:

> use tyun
switched to db tyun

> db
tyun

> db.createCollection("customers")
{ "ok" : 1 }

db.createCollection("crs", {capped: true, size: 65536, max: 1000000})

> db.createCollection("crs", {capped: true, size: 65536, max: 1000000})
{ "ok" : 1 }

> show collections
crs
customers

# drop 文档
db.<collection name>.drop()

> db.crs.drop()
true

> show collections
customers

// 插入单个文档
db.<collection name>.insert({document})

// 插入多个文档
db.<collection name>.insert(< [{document}, {document}, ..., {document}] >)


一个插入多个文档的例子:

> use playroom
switched to db playroom

> db
playroom

> show dbs
admin   0.000GB
config  0.000GB
tyun    0.000GB
local   0.000GB

db.crayons.insert([
    {
    "hex": "#EFDECD",
    "name": "Almond",
    "rgb": "(239, 222, 205)"
    },
    {
    "hex": "#CD9575",
    "name": "Antique Brass",
    "rgb": "(205, 149, 117)"
    },
    {
    "hex": "#FDD9B5",
    "name": "Apricot",
    "rgb": "(253, 217, 181)"
    },
    {
    "hex": "#78DBE2",
    "name": "Aquamarine",
    "rgb": "(120, 219, 226)"
    },
    {
    "hex": "#87A96B",
    "name": "Asparagus",
    "rgb": "(135, 169, 107)"
    },
    {
    "hex": "#FFA474",
    "name": "Atomic Tangerine",
    "rgb": "(255, 164, 116)"
    },
    {
    "hex": "#FAE7B5",
    "name": "Banana Mania",
    "rgb": "(250, 231, 181)"
    }
])

// 会有如下输出
BulkWriteResult({
 "writeErrors" : [ ],
 "writeConcernErrors" : [ ],
 "nInserted" : 7,
 "nUpserted" : 0,
 "nMatched" : 0,
 "nModified" : 0,
 "nRemoved" : 0,
 "upserted" : [ ]
})


接着查看集合:

> show collections
crayons

> db.crayons.find()
{ "_id" : ObjectId("5f3e2cc8f6abe840587e967b"), "hex" : "#EFDECD", "name" : "Almond", "rgb" : "(239, 222, 205)" }
{ "_id" : ObjectId("5f3e2cc8f6abe840587e967c"), "hex" : "#CD9575", "name" : "Antique Brass", "rgb" : "(205, 149, 117)" }
{ "_id" : ObjectId("5f3e2cc8f6abe840587e967d"), "hex" : "#FDD9B5", "name" : "Apricot", "rgb" : "(253, 217, 181)" }
{ "_id" : ObjectId("5f3e2cc8f6abe840587e967e"), "hex" : "#78DBE2", "name" : "Aquamarine", "rgb" : "(120, 219, 226)" }
{ "_id" : ObjectId("5f3e2cc8f6abe840587e967f"), "hex" : "#87A96B", "name" : "Asparagus", "rgb" : "(135, 169, 107)" }
{ "_id" : ObjectId("5f3e2cc8f6abe840587e9680"), "hex" : "#FFA474", "name" : "Atomic Tangerine", "rgb" : "(255, 164, 116)" }
{ "_id" : ObjectId("5f3e2cc8f6abe840587e9681"), "hex" : "#FAE7B5", "name" : "Banana Mania", "rgb" : "(250, 231, 181)" }

// drop
db.crayons.drop()

> db
playroom

> db.dropDatabase()
{ "dropped" : "playroom", "ok" : 1 }

文档查询

前面的内容是关于如何创建集合及创建文档,接下来的篇幅将要介绍文档的查询。准备测试数据:

> use test
switched to db test

db.oscars.insert([
  { "year": "1927",
    "title": "Wings",
    "imdbId": "tt0018578",
    "releaseDate": "1927-05-19T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1927,
    "releaseMonth": 4,
    "releaseDay": 19
  },
  { "year": "1929",
    "title": "The Broadway Melody",
    "imdbId": "tt0019729",
    "releaseDate": "1929-02-01T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1929,
    "releaseMonth": 1,
    "releaseDay": 1
  },
  { "year": "1930",
    "title": "All Quiet on the Western Front",
    "imdbId": "tt0020629",
    "releaseDate": "1930-04-21T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1930,
    "releaseMonth": 3,
    "releaseDay": 21
  },
  { "year": "1931",
    "title": "Cimarron",
    "imdbId": "tt0021746",
    "releaseDate": "1931-01-26T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1931,
    "releaseMonth": 0,
    "releaseDay": 26
  },
  { "year": "1932",
    "title": "Grand Hotel",
    "imdbId": "tt0022958",
    "releaseDate": "1932-04-12T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1932,
    "releaseMonth": 3,
    "releaseDay": 12
  },
  { "year": "1933",
    "title": "Cavalcade",
    "imdbId": "tt0023876",
    "releaseDate": "1933-01-05T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1933,
    "releaseMonth": 0,
    "releaseDay": 5
  },
  { "year": "1934",
    "title": "It Happened One Night",
    "imdbId": "tt0025316",
    "releaseDate": "1934-02-22T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1934,
    "releaseMonth": 1,
    "releaseDay": 22
  },
  { "year": "1935",
    "title": "Mutiny on the Bounty",
    "imdbId": "tt0026752",
    "releaseDate": "1935-11-08T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1935,
    "releaseMonth": 10,
    "releaseDay": 8
  },
  { "year": "1936",
    "title": "The Great Ziegfeld",
    "imdbId": "tt0027698",
    "releaseDate": "1936-03-22T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1936,
    "releaseMonth": 2,
    "releaseDay": 22
  },
  { "year": "1937",
    "title": "The Life of Emile Zola",
    "imdbId": "tt0029146",
    "releaseDate": "1937-08-11T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1937,
    "releaseMonth": 7,
    "releaseDay": 11
  },
  { "year": "1938",
    "title": "You Can't Take It with You",
    "imdbId": "tt0030993",
    "releaseDate": "1938-08-23T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1938,
    "releaseMonth": 7,
    "releaseDay": 23
  },
  { "year": "1939",
    "title": "Gone with the Wind",
    "imdbId": "tt0031381",
    "releaseDate": "1939-12-28T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1939,
    "releaseMonth": 11,
    "releaseDay": 28
  },
  { "year": "1940",
    "title": "Rebecca",
    "imdbId": "tt0032976",
    "releaseDate": "1940-03-27T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1940,
    "releaseMonth": 2,
    "releaseDay": 27
  },
  { "year": "1941",
    "title": "How Green Was My Valley",
    "imdbId": "tt0033729",
    "releaseDate": "1941-10-28T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1941,
    "releaseMonth": 9,
    "releaseDay": 28
  },
  { "year": "1942",
    "title": "Mrs. Miniver",
    "imdbId": "tt0035093",
    "releaseDate": "1942-07-22T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1942,
    "releaseMonth": 6,
    "releaseDay": 22
  },
  { "year": "1943",
    "title": "Casablanca",
    "imdbId": "tt0034583",
    "releaseDate": "1942-11-26T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1942,
    "releaseMonth": 10,
    "releaseDay": 26
  },
  { "year": "1944",
    "title": "Going My Way",
    "imdbId": "tt0036872",
    "releaseDate": "1944-08-16T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1944,
    "releaseMonth": 7,
    "releaseDay": 16
  },
  { "year": "1945",
    "title": "The Lost Weekend",
    "imdbId": "tt0037884",
    "releaseDate": "1945-11-29T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1945,
    "releaseMonth": 10,
    "releaseDay": 29
  },
  { "year": "1946",
    "title": "The Best Years of Our Lives",
    "imdbId": "tt0036868",
    "releaseDate": "1946-12-25T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1946,
    "releaseMonth": 11,
    "releaseDay": 25
  },
  { "year": "1947",
    "title": "Gentleman's Agreement",
    "imdbId": "tt0039416",
    "releaseDate": "1947-11-11T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1947,
    "releaseMonth": 10,
    "releaseDay": 11
  },
  { "year": "1948",
    "title": "Hamlet",
    "imdbId": "tt0040416",
    "releaseDate": "1948-10-27T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1948,
    "releaseMonth": 9,
    "releaseDay": 27
  },
  { "year": "1949",
    "title": "All the Kings Men",
    "imdbId": "tt0041113",
    "releaseDate": "1949-11-08T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1949,
    "releaseMonth": 10,
    "releaseDay": 8
  },
  { "year": "1950",
    "title": "All About Eve",
    "imdbId": "tt0042192",
    "releaseDate": "1950-10-13T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1950,
    "releaseMonth": 9,
    "releaseDay": 13
  },
  { "year": "1951",
    "title": "An American in Paris",
    "imdbId": "tt0043278",
    "releaseDate": "1951-10-04T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1951,
    "releaseMonth": 9,
    "releaseDay": 4
  },
  { "year": "1952",
    "title": "The Greatest Show on Earth",
    "imdbId": "tt0044672",
    "releaseDate": "1952-01-10T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1952,
    "releaseMonth": 0,
    "releaseDay": 10
  },
  { "year": "1953",
    "title": "From Here to Eternity",
    "imdbId": "tt0045793",
    "releaseDate": "1953-09-30T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1953,
    "releaseMonth": 8,
    "releaseDay": 30
  },
  { "year": "1954",
    "title": "On the Waterfront",
    "imdbId": "tt0047296",
    "releaseDate": "1954-07-28T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1954,
    "releaseMonth": 6,
    "releaseDay": 28
  },
  { "year": "1955",
    "title": "Marty",
    "imdbId": "tt0048356",
    "releaseDate": "1955-07-15T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1955,
    "releaseMonth": 6,
    "releaseDay": 15
  },
  { "year": "1956",
    "title": "Around the World in 80 Days",
    "imdbId": "tt0048960",
    "releaseDate": "1956-12-22T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1956,
    "releaseMonth": 11,
    "releaseDay": 22
  },
  { "year": "1957",
    "title": "The Bridge on the River Kwai",
    "imdbId": "tt0050212",
    "releaseDate": "1957-12-19T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1957,
    "releaseMonth": 11,
    "releaseDay": 19
  },
  { "year": "1958",
    "title": "Gigi",
    "imdbId": "tt0051658",
    "releaseDate": "1958-07-10T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1958,
    "releaseMonth": 6,
    "releaseDay": 10
  },
  { "year": "1959",
    "title": "Ben-Hur",
    "imdbId": "tt0052618",
    "releaseDate": "1959-11-18T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1959,
    "releaseMonth": 10,
    "releaseDay": 18
  },
  { "year": "1960",
    "title": "The Apartment",
    "imdbId": "tt0053604",
    "releaseDate": "1960-06-21T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1960,
    "releaseMonth": 5,
    "releaseDay": 21
  },
  { "year": "1961",
    "title": "West Side Story",
    "imdbId": "tt0055614",
    "releaseDate": "1961-12-13T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1961,
    "releaseMonth": 11,
    "releaseDay": 13
  },
  { "year": "1962",
    "title": "Lawrence of Arabia",
    "imdbId": "tt0056172",
    "releaseDate": "1962-12-21T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1962,
    "releaseMonth": 11,
    "releaseDay": 21
  },
  { "year": "1963",
    "title": "Tom Jones",
    "imdbId": "tt0057590",
    "releaseDate": "1963-10-24T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1963,
    "releaseMonth": 9,
    "releaseDay": 24
  },
  { "year": "1964",
    "title": "My Fair Lady",
    "imdbId": "tt0058385",
    "releaseDate": "1964-10-28T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1964,
    "releaseMonth": 9,
    "releaseDay": 28
  },
  { "year": "1965",
    "title": "The Sound of Music",
    "imdbId": "tt0059742",
    "releaseDate": "1965-03-10T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1965,
    "releaseMonth": 2,
    "releaseDay": 10
  },
  { "year": "1966",
    "title": "A Man for All Seasons",
    "imdbId": "tt0060665",
    "releaseDate": "1966-12-14T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1966,
    "releaseMonth": 11,
    "releaseDay": 14
  },
  { "year": "1967",
    "title": "In the Heat of the Night",
    "imdbId": "tt0061811",
    "releaseDate": "1967-08-23T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1967,
    "releaseMonth": 7,
    "releaseDay": 23
  },
  { "year": "1968",
    "title": "Oliver!",
    "imdbId": "tt0063385",
    "releaseDate": "1968-12-20T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1968,
    "releaseMonth": 11,
    "releaseDay": 20
  },
  { "year": "1969",
    "title": "Midnight Cowboy",
    "imdbId": "tt0064665",
    "releaseDate": "1969-05-25T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1969,
    "releaseMonth": 4,
    "releaseDay": 25
  },
  { "year": "1970",
    "title": "Patton",
    "imdbId": "tt0066206",
    "releaseDate": "1970-02-18T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1970,
    "releaseMonth": 1,
    "releaseDay": 18
  },
  { "year": "1971",
    "title": "The French Connection",
    "imdbId": "tt0067116",
    "releaseDate": "1971-10-07T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1971,
    "releaseMonth": 9,
    "releaseDay": 7
  },
  { "year": "1972",
    "title": "The Godfather",
    "imdbId": "tt0068646",
    "releaseDate": "1972-03-22T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1972,
    "releaseMonth": 2,
    "releaseDay": 22
  },
  { "year": "1973",
    "title": "The Sting",
    "imdbId": "tt0070735",
    "releaseDate": "1973-12-25T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1973,
    "releaseMonth": 11,
    "releaseDay": 25
  },
  { "year": "1974",
    "title": "The Godfather Part II",
    "imdbId": "tt0071562",
    "releaseDate": "1974-12-18T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1974,
    "releaseMonth": 11,
    "releaseDay": 18
  },
  { "year": "1975",
    "title": "One Flew over the Cuckoo's Nest",
    "imdbId": "tt0073486",
    "releaseDate": "1975-11-19T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1975,
    "releaseMonth": 10,
    "releaseDay": 19
  },
  { "year": "1976",
    "title": "Rocky",
    "imdbId": "tt0075148",
    "releaseDate": "1976-11-21T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1976,
    "releaseMonth": 10,
    "releaseDay": 21
  },
  { "year": "1977",
    "title": "Annie Hall",
    "imdbId": "tt0075686",
    "releaseDate": "1977-04-20T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1977,
    "releaseMonth": 3,
    "releaseDay": 20
  },
  { "year": "1978",
    "title": "The Deer Hunter",
    "imdbId": "tt0077416",
    "releaseDate": "1978-12-08T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1978,
    "releaseMonth": 11,
    "releaseDay": 8
  },
  { "year": "1979",
    "title": "Kramer vs. Kramer",
    "imdbId": "tt0079417",
    "releaseDate": "1979-12-19T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1979,
    "releaseMonth": 11,
    "releaseDay": 19
  },
  { "year": "1980",
    "title": "Ordinary People",
    "imdbId": "tt0081283",
    "releaseDate": "1980-09-26T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1980,
    "releaseMonth": 8,
    "releaseDay": 26
  },
  { "year": "1981",
    "title": "Chariots of Fire",
    "imdbId": "tt0082158",
    "releaseDate": "1981-10-09T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1981,
    "releaseMonth": 9,
    "releaseDay": 9
  },
  { "year": "1982",
    "title": "Gandhi",
    "imdbId": "tt0083987",
    "releaseDate": "1982-12-07T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1982,
    "releaseMonth": 11,
    "releaseDay": 7
  },
  { "year": "1983",
    "title": "Terms of Endearment",
    "imdbId": "tt0086425",
    "releaseDate": "1983-11-20T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1983,
    "releaseMonth": 10,
    "releaseDay": 20
  },
  { "year": "1984",
    "title": "Amadeus",
    "imdbId": "tt0086879",
    "releaseDate": "1984-09-06T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1984,
    "releaseMonth": 8,
    "releaseDay": 6
  },
  { "year": "1985",
    "title": "Out of Africa",
    "imdbId": "tt0089755",
    "releaseDate": "1985-12-10T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1985,
    "releaseMonth": 11,
    "releaseDay": 10
  },
  { "year": "1986",
    "title": "Platoon",
    "imdbId": "tt0091763",
    "releaseDate": "1986-12-19T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1986,
    "releaseMonth": 11,
    "releaseDay": 19
  },
  { "year": "1987",
    "title": "The Last Emperor",
    "imdbId": "tt0093389",
    "releaseDate": "1987-11-19T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1987,
    "releaseMonth": 10,
    "releaseDay": 19
  },
  { "year": "1988",
    "title": "Rain Man",
    "imdbId": "tt0095953",
    "releaseDate": "1988-12-14T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1988,
    "releaseMonth": 11,
    "releaseDay": 14
  },
  { "year": "1989",
    "title": "Driving Miss Daisy",
    "imdbId": "tt0097239",
    "releaseDate": "1989-12-15T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1989,
    "releaseMonth": 11,
    "releaseDay": 15
  },
  { "year": "1990",
    "title": "Dances With Wolves",
    "imdbId": "tt0099348",
    "releaseDate": "1990-10-19T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1990,
    "releaseMonth": 9,
    "releaseDay": 19
  },
  { "year": "1991",
    "title": "The Silence of the Lambs",
    "imdbId": "tt0102926",
    "releaseDate": "1991-01-30T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1991,
    "releaseMonth": 0,
    "releaseDay": 30
  },
  { "year": "1992",
    "title": "Unforgiven",
    "imdbId": "tt0105695",
    "releaseDate": "1992-08-03T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1992,
    "releaseMonth": 7,
    "releaseDay": 3
  },
  { "year": "1993",
    "title": "Schindler's List",
    "imdbId": "tt0108052",
    "releaseDate": "1993-11-30T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1993,
    "releaseMonth": 10,
    "releaseDay": 30
  },
  { "year": "1994",
    "title": "Forrest Gump",
    "imdbId": "tt0109830",
    "releaseDate": "1994-06-23T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1994,
    "releaseMonth": 5,
    "releaseDay": 23
  },
  { "year": "1995",
    "title": "Braveheart",
    "imdbId": "tt0112573",
    "releaseDate": "1995-05-19T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1995,
    "releaseMonth": 4,
    "releaseDay": 19
  },
  { "year": "1996",
    "title": "The English Patient",
    "imdbId": "tt0116209",
    "releaseDate": "1996-11-12T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1996,
    "releaseMonth": 10,
    "releaseDay": 12
  },
  { "year": "1997",
    "title": "Titanic",
    "imdbId": "tt0120338",
    "releaseDate": "1997-12-14T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1997,
    "releaseMonth": 11,
    "releaseDay": 14
  },
  { "year": "1998",
    "title": "Shakespeare in Love",
    "imdbId": "tt0138097",
    "releaseDate": "1998-12-08T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1998,
    "releaseMonth": 11,
    "releaseDay": 8
  },
  { "year": "1999",
    "title": "American Beauty",
    "imdbId": "tt0169547",
    "releaseDate": "1999-09-08T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 1999,
    "releaseMonth": 8,
    "releaseDay": 8
  },
  { "year": "2000",
    "title": "Gladiator",
    "imdbId": "tt0172495",
    "releaseDate": "2000-05-01T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 2000,
    "releaseMonth": 4,
    "releaseDay": 1
  },
  { "year": "2001",
    "title": "A Beautiful Mind",
    "imdbId": "tt0268978",
    "releaseDate": "2001-12-13T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 2001,
    "releaseMonth": 11,
    "releaseDay": 13
  },
  { "year": "2002",
    "title": "Chicago",
    "imdbId": "tt0299658",
    "releaseDate": "2002-12-18T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 2002,
    "releaseMonth": 11,
    "releaseDay": 18
  },
  { "year": "2003",
    "title": "The Lord of the Rings: The Return of the King",
    "imdbId": "tt0167260",
    "releaseDate": "2003-12-17T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 2003,
    "releaseMonth": 11,
    "releaseDay": 17
  },
  { "year": "2004",
    "title": "Million Dollar Baby",
    "imdbId": "tt0405159",
    "releaseDate": "2004-12-15T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 2004,
    "releaseMonth": 11,
    "releaseDay": 15
  },
  { "year": "2005",
    "title": "Crash",
    "imdbId": "tt0375679",
    "releaseDate": "2005-04-26T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 2005,
    "releaseMonth": 3,
    "releaseDay": 26
  },
  { "year": "2006",
    "title": "The Departed",
    "imdbId": "tt0407887",
    "releaseDate": "2006-09-26T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 2006,
    "releaseMonth": 8,
    "releaseDay": 26
  },
  { "year": "2007",
    "title": "No Country for Old Men",
    "imdbId": "tt0477348",
    "releaseDate": "2007-11-04T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 2007,
    "releaseMonth": 10,
    "releaseDay": 4
  },
  { "year": "2008",
    "title": "Slumdog Millionaire",
    "imdbId": "tt1010048",
    "releaseDate": "2008-11-12T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 2008,
    "releaseMonth": 10,
    "releaseDay": 12
  },
  { "year": "2009",
    "title": "The Hurt Locker",
    "imdbId": "tt1655246",
    "releaseDate": "2009-01-29T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 2009,
    "releaseMonth": 0,
    "releaseDay": 29
  },
  { "year": "2010",
    "title": "The King's Speech",
    "imdbId": "tt1504320",
    "releaseDate": "2010-12-24T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 2010,
    "releaseMonth": 11,
    "releaseDay": 24
  },
  { "year": "2011",
    "title": "The Artist",
    "imdbId": "tt1655442",
    "releaseDate": "2011-11-23T05:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 2011,
    "releaseMonth": 10,
    "releaseDay": 23
  },
  { "year": "2012",
    "title": "Argo",
    "imdbId": "tt1024648",
    "releaseDate": "2012-10-04T04:00:00.000Z",
    "releaseCountry": "USA",
    "releaseYear": 2012,
    "releaseMonth": 9,
    "releaseDay": 4
  }])

find

​find​​ 的语法为:

db.collection.find(query, projection)

# 查询的语法为
db.<collection name>.find()


下面是一些具体的示例:

> show collections
books
customer
inventory
oscars

> db.oscars.find()
{ "_id" : ObjectId("62e3868b6afabf9443056123"), "year" : "1927", "title" : "Wings", "imdbId" : "tt0018578", "releaseDate" : "1927-05-19T05:00:00.000Z", "releaseCountry" : "USA", "releaseYear" : 1927, "releaseMonth" : 4, "releaseDay" : 19 }
{ "_id" : ObjectId("62e3868b6afabf9443056124"), "year" : "1929", "title" : "The Broadway Melody", "imdbId" : "tt0019729", "releaseDate" : "1929-02-01T05:00:00.000Z", "releaseCountry" : "USA", "releaseYear" : 1929, "releaseMonth" : 1, "releaseDay" : 1 }
{ "_id" : ObjectId("62e3868b6afabf9443056125"), "year" : "1930", "title" : "All Quiet on the Western Front", "imdbId" : "tt0020629", "releaseDate" : "1930-04-21T04:00:00.000Z", "releaseCountry" : "USA", "releaseYear" : 1930, "releaseMonth" : 3, "releaseDay" : 21 }
{ "_id" : ObjectId("62e3868b6afabf9443056126"), "year" : "1931", "title" : "Cimarron", "imdbId" : "tt0021746", "releaseDate" : "1931-01-26T05:00:00.000Z", "releaseCountry" : "USA", "releaseYear" : 1931, "releaseMonth" : 0, "releaseDay" : 26 }
{ "_id" : ObjectId("62e3868b6afabf9443056127"), "year" : "1932", "title" : "Grand Hotel", "imdbId" : "tt0022958", "releaseDate" : "1932-04-12T04:00:00.000Z", "releaseCountry" : "USA", "releaseYear" : 1932, "releaseMonth" : 3, "releaseDay" : 12 }
{ "_id" : ObjectId("62e3868b6afabf9443056128"), "year" : "1933", "title" : "Cavalcade", "imdbId" : "tt0023876", "releaseDate" : "1933-01-05T05:00:00.000Z", "releaseCountry" : "USA", "releaseYear" : 1933, "releaseMonth" : 0, "releaseDay" : 5 }
{ "_id" : ObjectId("62e3868b6afabf9443056129"), "year" : "1934", "title" : "It Happened One Night", "imdbId" : "tt0025316", "releaseDate" : "1934-02-22T05:00:00.000Z", "releaseCountry" : "USA", "releaseYear" : 1934, "releaseMonth" : 1, "releaseDay" : 22 }
{ "_id" : ObjectId("62e3868b6afabf944305612a"), "year" : "1935", "title" : "Mutiny on the Bounty", "imdbId" : "tt0026752", "releaseDate" : "1935-11-08T05:00:00.000Z", "releaseCountry" : "USA", "releaseYear" : 1935, "releaseMonth" : 10, "releaseDay" : 8 }
{ "_id" : ObjectId("62e3868b6afabf944305612b"), "year" : "1936", "title" : "The Great Ziegfeld", "imdbId" : "tt0027698", "releaseDate" : "1936-03-22T04:00:00.000Z", "releaseCountry" : "USA", "releaseYear" : 1936, "releaseMonth" : 2, "releaseDay" : 22 }
{ "_id" : ObjectId("62e3868b6afabf944305612c"), "year" : "1937", "title" : "The Life of Emile Zola", "imdbId" : "tt0029146", "releaseDate" : "1937-08-11T04:00:00.000Z", "releaseCountry" : "USA", "releaseYear" : 1937, "releaseMonth" : 7, "releaseDay" : 11 }
{ "_id" : ObjectId("62e3868b6afabf944305612d"), "year" : "1938", "title" : "You Can't Take It with You", "imdbId" : "tt0030993", "releaseDate" : "1938-08-23T04:00:00.000Z", "releaseCountry" : "USA", "releaseYear" : 1938, "releaseMonth" : 7, "releaseDay" : 23 }
{ "_id" : ObjectId("62e3868b6afabf944305612e"), "year" : "1939", "title" : "Gone with the Wind", "imdbId" : "tt0031381", "releaseDate" : "1939-12-28T05:00:00.000Z", "releaseCountry" : "USA", "releaseYear" : 1939, "releaseMonth" : 11, "releaseDay" : 28 }
{ "_id" : ObjectId("62e3868b6afabf944305612f"), "year" : "1940", "title" : "Rebecca", "imdbId" : "tt0032976", "releaseDate" : "1940-03-27T04:00:00.000Z", "releaseCountry" : "USA", "releaseYear" : 1940, "releaseMonth" : 2, "releaseDay" : 27 }
{ "_id" : ObjectId("62e3868b6afabf9443056130"), "year" : "1941", "title" : "How Green Was My Valley", "imdbId" : "tt0033729", "releaseDate" : "1941-10-28T05:00:00.000Z", "releaseCountry" : "USA", "releaseYear" : 1941, "releaseMonth" : 9, "releaseDay" : 28 }
{ "_id" : ObjectId("62e3868b6afabf9443056131"), "year" : "1942", "title" : "Mrs. Miniver", "imdbId" : "tt0035093", "releaseDate" : "1942-07-22T04:00:00.000Z", "releaseCountry" : "USA", "releaseYear" : 1942, "releaseMonth" : 6, "releaseDay" : 22 }
{ "_id" : ObjectId("62e3868b6afabf9443056132"), "year" : "1943", "title" : "Casablanca", "imdbId" : "tt0034583", "releaseDate" : "1942-11-26T05:00:00.000Z", "releaseCountry" : "USA", "releaseYear" : 1942, "releaseMonth" : 10, "releaseDay" : 26 }
{ "_id" : ObjectId("62e3868b6afabf9443056133"), "year" : "1944", "title" : "Going My Way", "imdbId" : "tt0036872", "releaseDate" : "1944-08-16T04:00:00.000Z", "releaseCountry" : "USA", "releaseYear" : 1944, "releaseMonth" : 7, "releaseDay" : 16 }
{ "_id" : ObjectId("62e3868b6afabf9443056134"), "year" : "1945", "title" : "The Lost Weekend", "imdbId" : "tt0037884", "releaseDate" : "1945-11-29T05:00:00.000Z", "releaseCountry" : "USA", "releaseYear" : 1945, "releaseMonth" : 10, "releaseDay" : 29 }
{ "_id" : ObjectId("62e3868b6afabf9443056135"), "year" : "1946", "title" : "The Best Years of Our Lives", "imdbId" : "tt0036868", "releaseDate" : "1946-12-25T05:00:00.000Z", "releaseCountry" : "USA", "releaseYear" : 1946, "releaseMonth" : 11, "releaseDay" : 25 }
{ "_id" : ObjectId("62e3868b6afabf9443056136"), "year" : "1947", "title" : "Gentleman's Agreement", "imdbId" : "tt0039416", "releaseDate" : "1947-11-11T05:00:00.000Z", "releaseCountry" : "USA", "releaseYear" : 1947, "releaseMonth" : 10, "releaseDay" : 11 }
Type "it" for more2 }

find one

可以使用 findOne() 方法查询一条文档:

# 查询语法为
db.<collection name>.findOne()

> db.oscars.findOne()
{
 "_id" : ObjectId("62e3868b6afabf9443056123"),
 "year" : "1927",
 "title" : "Wings",
 "imdbId" : "tt0018578",
 "releaseDate" : "1927-05-19T05:00:00.000Z",
 "releaseCountry" : "USA",
 "releaseYear" : 1927,
 "releaseMonth" : 4,
 "releaseDay" : 19
}

find specific

查询指定的文档:

> db.oscars.find({title: "Wings"})
{ "_id" : ObjectId("62e3868b6afabf9443056123"), "year" : "1927", "title" : "Wings", "imdbId" : "tt0018578", "releaseDate" : "1927-05-19T05:00:00.000Z", "releaseCountry" : "USA", "releaseYear" : 1927, "releaseMonth" : 4, "releaseDay" : 19 }


我们可以用任何一种方式来做:“title” 或 title。JSON 规范是将名称(对象名称-值对)包含在双引号中。

and

db.customers.find({$and: [{name:"Bond"}, {age:32}]})
> db.customers.find({$and: [{name:"Bond"}, {age:{$lt:20}}]}) # 没有符合条件的
> db.customers.find({$and: [{name:"Bond"}, {age:{$gt:20}}]})
{ "_id" : ObjectId("5f3e33a5f6abe840587e9682"), "role" : "double-zero", "name" : "Bond", "age" : 32 }

or

> db.customers.find({$or: [{name:"Bond"}, {age:67}]})
{ "_id" : ObjectId("5f3e33a5f6abe840587e9682"), "role" : "double-zero", "name" : "Bond", "age" : 32 }
{ "_id" : ObjectId("5f3e33a5f6abe840587e9684"), "role" : "citizen", "name" : "Q", "age" : 67 }

> db.customers.find({$or: [{name:"Bond"}, {age:{$lt:20}}]})
{ "_id" : ObjectId("5f3e33a5f6abe840587e9682"), "role" : "double-zero", "name" : "Bond", "age" : 32 }

> db.customers.find({$or: [{name:"Bond"}, {age:{$gt:32}}]})
{ "_id" : ObjectId("5f3e33a5f6abe840587e9682"), "role" : "double-zero", "name" : "Bond", "age" : 32 }
{ "_id" : ObjectId("5f3e33a5f6abe840587e9684"), "role" : "citizen", "name" : "Q", "age" : 67 }
{ "_id" : ObjectId("5f3e33a5f6abe840587e9685"), "role" : "citizen", "name" : "M", "age" : 57 }
{ "_id" : ObjectId("5f3e33a5f6abe840587e9686"), "role" : "citizen", "name" : "Dr. No", "age" : 52 }

and or

andor 还可以一起使用。下面是一些具体的示例:

> db.customers.find({role: "citizen"})
{ "_id" : ObjectId("5f3e33a5f6abe840587e9683"), "role" : "citizen", "name" : "Moneypenny", "age" : 32 }
{ "_id" : ObjectId("5f3e33a5f6abe840587e9684"), "role" : "citizen", "name" : "Q", "age" : 67 }
{ "_id" : ObjectId("5f3e33a5f6abe840587e9685"), "role" : "citizen", "name" : "M", "age" : 57 }
{ "_id" : ObjectId("5f3e33a5f6abe840587e9686"), "role" : "citizen", "name" : "Dr. No", "age" : 52 }

> db.customers.find({age: 52})
{ "_id" : ObjectId("5f3e33a5f6abe840587e9686"), "role" : "citizen", "name" : "Dr. No", "age" : 52 }

> db.customers.find({$and: [{role:"citizen"}, {age:52}]})
{ "_id" : ObjectId("5f3e33a5f6abe840587e9686"), "role" : "citizen", "name" : "Dr. No", "age" : 52 }

> db.customers.find({$or: [{role:"citizen"}, {age:52}]})
{ "_id" : ObjectId("5f3e33a5f6abe840587e9683"), "role" : "citizen", "name" : "Moneypenny", "age" : 32 }
{ "_id" : ObjectId("5f3e33a5f6abe840587e9684"), "role" : "citizen", "name" : "Q", "age" : 67 }
{ "_id" : ObjectId("5f3e33a5f6abe840587e9685"), "role" : "citizen", "name" : "M", "age" : 57 }
{ "_id" : ObjectId("5f3e33a5f6abe840587e9686"), "role" : "citizen", "name" : "Dr. No", "age" : 52 }

> db.customers.find({$or: [{role:"citizen"}, {age:52}, {name:"Bond"}]})
{ "_id" : ObjectId("5f3e33a5f6abe840587e9682"), "role" : "double-zero", "name" : "Bond", "age" : 32 }
{ "_id" : ObjectId("5f3e33a5f6abe840587e9683"), "role" : "citizen", "name" : "Moneypenny", "age" : 32 }
{ "_id" : ObjectId("5f3e33a5f6abe840587e9684"), "role" : "citizen", "name" : "Q", "age" : 67 }
{ "_id" : ObjectId("5f3e33a5f6abe840587e9685"), "role" : "citizen", "name" : "M", "age" : 57 }
{ "_id" : ObjectId("5f3e33a5f6abe840587e9686"), "role" : "citizen", "name" : "Dr. No", "age" : 52 }

db.customers.find({$or:[
{ $and : [ { role : "citizen" }, { age : 32 } ] },
{ $and : [ { role : "citizen" }, { age : 67 } ] }
]})

{ "_id" : ObjectId("5f3e33a5f6abe840587e9683"), "role" : "citizen", "name" : "Moneypenny", "age" : 32 }
{ "_id" : ObjectId("5f3e33a5f6abe840587e9684"), "role" : "citizen", "name" : "Q", "age" : 67 }

# 拆解上面的查询
> db.customers.find({$and: [{role:"citizen"}, {age:32}]})
{ "_id" : ObjectId("5f3e33a5f6abe840587e9683"), "role" : "citizen", "name" : "Moneypenny", "age" : 32 }
> db.customers.find({$and: [{role:"citizen"}, {age:67}]})
{ "_id" : ObjectId("5f3e33a5f6abe840587e9684"), "role" : "citizen", "name" : "Q", "age" : 67 }
# 最后通过 or 组合起来了

regex

还可以使用 regex 以支持正则。示例如下:

> db.customers.find({name: {$regex: '^M'}})
{ "_id" : ObjectId("5f3e33a5f6abe840587e9683"), "role" : "citizen", "name" : "Moneypenny", "age" : 32 }
{ "_id" : ObjectId("5f3e33a5f6abe840587e9685"), "role" : "citizen", "name" : "M", "age" : 57 }

pretty

该函数可以美化输出。示例如下:

> db.customers.find().pretty()
{
 "_id" : ObjectId("5f3e33a5f6abe840587e9682"),
 "role" : "double-zero",
 "name" : "Bond",
 "age" : 32
}
{
 "_id" : ObjectId("5f3e33a5f6abe840587e9683"),
 "role" : "citizen",
 "name" : "Moneypenny",
 "age" : 32
}
{
 "_id" : ObjectId("5f3e33a5f6abe840587e9684"),
 "role" : "citizen",
 "name" : "Q",
 "age" : 67
}
{
 "_id" : ObjectId("5f3e33a5f6abe840587e9685"),
 "role" : "citizen",
 "name" : "M",
 "age" : 57
}
{
 "_id" : ObjectId("5f3e33a5f6abe840587e9686"),
 "role" : "citizen",
 "name" : "Dr. No",
 "age" : 52
}

operators 运算符

自建 MongoDB 实战 | MongoDB 文档查询-鸿蒙开发者社区

文档更新

update & save

  • update 会更新一条记录
  • save 会覆写一条记录

update

update 的语法为:

db.<collection mame>.update(<selection criteria>, <update data>, <optional options>)


示例如下:

db.blocks.find()
{ _id: ObjectId("62ef8bcf928608fc90caeb01"),
  timestamp: 2017-06-24T17:19:04.000Z,
  block_height: 3923788,
  number_transactions: 28,
  number_internal_transactions: 4,
  difficulty: 882071747513072,
  block_hash: Binary(Buffer.from("307838396432333563346532653465343937383434306633636331393636663166666233343362396235636665633965356365626333333166623831306264656433", "hex"), 0),
  gas_used: 4694483 }
{ _id: ObjectId("62ef8bcf928608fc90caeb02"),
  timestamp: 2017-06-24T17:19:05.000Z,
  block_height: 3923787,
  number_transactions: 26,
  number_internal_transactions: 2,
  difficulty: 882365150918446,
  block_hash: Binary(Buffer.from("307832326430633434653431326130643063313834353034306463396331646365633866393164373630333834383535613632323832313233653938626564653761", "hex"), 0),
  gas_used: 935704 }
{ _id: ObjectId("62ef8bcf928608fc90caeb03"),
  timestamp: 2017-06-24T17:19:06.000Z,
  block_height: 3923786,
  number_transactions: 34,
  number_internal_transactions: 1,
  difficulty: 881797146951814,
  block_hash: Binary(Buffer.from("307861636534336239663863656337326461333239663834313665336436383433353932373261363062303364666563333563653361386331616464383663336138", "hex"), 0),
  gas_used: 729879 }
{ _id: ObjectId("62ef8bcf928608fc90caeb04"),
  timestamp: 2017-06-24T17:19:07.000Z,
  block_height: 3923768,
  number_transactions: 88,
  number_internal_transactions: 11,
  difficulty: 881046857387125,
  block_hash: Binary(Buffer.from("307866323930303666333063623837303062303063393964663839373736633363613164363637326661313366316135333630393865613366313732373234646531", "hex"), 0),
  gas_used: 4671277 }
{ _id: ObjectId("62ef8bcf928608fc90caeb05"),
  timestamp: 2017-06-24T17:19:08.000Z,
  block_height: 3923785,
  number_transactions: 16,
  number_internal_transactions: 1,
  difficulty: 881229420195513,
  block_hash: Binary(Buffer.from("307833376130643963303633396561386164343633616330613234333230303136336231343034323239656439366535626635366464306138653266366138393164", "hex"), 0),
  gas_used: 383869 }
{ _id: ObjectId("62ef8bcf928608fc90caeb06"),
  timestamp: 2017-06-24T17:19:09.000Z,
  block_height: 3923784,
  number_transactions: 76,
  number_internal_transactions: 21,
  difficulty: 881522412107327,
  block_hash: Binary(Buffer.from("307836663036356465373236383436383738343737363666613538646364336535393039633730366639633662616339613138323832323632626662343236363961", "hex"), 0),
  gas_used: 4667547 }
{ _id: ObjectId("62ef8bcf928608fc90caeb07"),
  timestamp: 2017-06-24T17:19:10.000Z,
  block_height: 3923783,
  number_transactions: 34,
  number_internal_transactions: 7,
  difficulty: 882246542042567,
  block_hash: Binary(Buffer.from("307832373365383062663363663361623833316631666335653163323665313034386462313137643966616438633038636234396530333636343737343639326333", "hex"), 0),
  gas_used: 1778906 }
{ _id: ObjectId("62ef8bcf928608fc90caeb08"),
  timestamp: 2017-06-24T17:19:11.000Z,
  block_height: 3923782,
  number_transactions: 3,
  number_internal_transactions: 0,
  difficulty: 882540030838527,
  block_hash: Binary(Buffer.from("307865323138353631653933326134633366316364376134633661343338303734356364613661366161393137663739303561393865316232316633363435346332", "hex"), 0),
  gas_used: 94845 }
{ _id: ObjectId("62ef8bcf928608fc90caeb09"),
  timestamp: 2017-06-24T17:19:12.000Z,
  block_height: 3923781,
  number_transactions: 17,
  number_internal_transactions: 7,
  difficulty: 881971941522984,
  block_hash: Binary(Buffer.from("307865336136363763383737356531613066323563643766626436613437333336303230303135393838363562663530393966626464363762386462346164386635", "hex"), 0),
  gas_used: 2539308 }
{ _id: ObjectId("62ef8bcf928608fc90caeb0a"),
  timestamp: 2017-06-24T17:19:13.000Z,
  block_height: 3923780,
  number_transactions: 38,
  number_internal_transactions: 7,
  difficulty: 881404129459425,
  block_hash: Binary(Buffer.from("307863646530613238366163373635303336316435373062356238313832366533346665633762356536393366396138663463303330633139666362646361393436", "hex"), 0),
  gas_used: 1731520 }
{ _id: ObjectId("62ef8bcf928608fc90caeb0b"),
  timestamp: 2017-06-24T17:19:14.000Z,
  block_height: 3923779,
  number_transactions: 32,
  number_internal_transactions: 6,
  difficulty: 881266690505953,
  block_hash: Binary(Buffer.from("307866663433666638333638333338656566366334323837656538306265346436353134313565343764623431386636356531323465623339356664376233656433", "hex"), 0),
  gas_used: 2330050 }
{ _id: ObjectId("62ef8bcf928608fc90caeb0c"),
  timestamp: 2017-06-24T17:19:15.000Z,
  block_height: 3923778,
  number_transactions: 49,
  number_internal_transactions: 10,
  difficulty: 881129251552481,
  block_hash: Binary(Buffer.from("307861613534356439343231303735326565356430356562303736626362383736613364643965303331646361656433323435643830623333316636656230633561", "hex"), 0),
  gas_used: 3391377 }
{ _id: ObjectId("62ef8bcf928608fc90caeb0d"),
  timestamp: 2017-06-24T17:19:16.000Z,
  block_height: 3923777,
  number_transactions: 78,
  number_internal_transactions: 7,
  difficulty: 881422194529931,
  block_hash: Binary(Buffer.from("307866353533336638623730653935633066366435373561333136363361386463313932613739333732663036383630343366316137396435333963616336393261", "hex"), 0),
  gas_used: 3096987 }
{ _id: ObjectId("62ef8bcf928608fc90caeb0e"),
  timestamp: 2017-06-24T17:19:17.000Z,
  block_height: 3923776,
  number_transactions: 80,
  number_internal_transactions: 23,
  difficulty: 881715280615822,
  block_hash: Binary(Buffer.from("307864333661616138646632373035663362353737383130633262363866303766376434366635303439333063333363646539663564643231373439313134383734", "hex"), 0),
  gas_used: 3906503 }
{ _id: ObjectId("62ef8bcf928608fc90caeb0f"),
  timestamp: 2017-06-24T17:19:18.000Z,
  block_height: 3923775,
  number_transactions: 32,
  number_internal_transactions: 12,
  difficulty: 881577841662350,
  block_hash: Binary(Buffer.from("307837356366323734313034356236626635646363653663356533363239643432336133653061386134613233633863356535323164616166356436356161653063", "hex"), 0),
  gas_used: 1273640 }
{ _id: ObjectId("62ef8bcf928608fc90caeb10"),
  timestamp: 2017-06-24T17:19:19.000Z,
  block_height: 3923774,
  number_transactions: 65,
  number_internal_transactions: 19,
  difficulty: 881871003784944,
  block_hash: Binary(Buffer.from("307839626431623539323237336365646636616130396664396363313766306533613930616466613363343538326366376131653664356537383566663762336135", "hex"), 0),
  gas_used: 3588872 }
{ _id: ObjectId("62ef8bcf928608fc90caeb11"),
  timestamp: 2017-06-24T17:19:21.000Z,
  block_height: 3923773,
  number_transactions: 7,
  number_internal_transactions: 0,
  difficulty: 882164309123035,
  block_hash: Binary(Buffer.from("307862373162363539653932643031626664383465616561303465323238653164616362303234313438336234653062326363376435363264303236643634336362", "hex"), 0),
  gas_used: 220241 }
{ _id: ObjectId("62ef8bcf928608fc90caeb12"),
  timestamp: 2017-06-24T17:19:22.000Z,
  block_height: 3923772,
  number_transactions: 22,
  number_internal_transactions: 14,
  difficulty: 882026870169563,
  block_hash: Binary(Buffer.from("307837383365373165323965666438613337313266393530303262366239643835333838613838346232316534653061393430346666643161323434366665363532", "hex"), 0),
  gas_used: 3655586 }
{ _id: ObjectId("62ef8bcf928608fc90caeb13"),
  timestamp: 2017-06-24T17:19:22.000Z,
  block_height: 3923771,
  number_transactions: 29,
  number_internal_transactions: 5,
  difficulty: 881459031298465,
  block_hash: Binary(Buffer.from("307833363961653233343232663934613132333937333763373833343861663133353239313339616531343763633832666364353564356332343335326464393232", "hex"), 0),
  gas_used: 4259974 }
{ _id: ObjectId("62ef8bcf928608fc90caeb14"),
  timestamp: 2017-06-24T17:19:23.000Z,
  block_height: 3923770,
  number_transactions: 51,
  number_internal_transactions: 18,
  difficulty: 881321592344993,
  block_hash: Binary(Buffer.from("307830353236326261343166383466383835663265636230636561653436326564356536396364376463323536626464613663346238663533323865623662636230", "hex"), 0),
  gas_used: 4639680 }

update 示例如下:

db.blocks.update({_id: ObjectId("62ef8bcf928608fc90caeb14")}, {$set: {block_height: 3923771}})

db.blocks.update({difficulty: 881459031298465}, {$set: {block_height: 123456}})

db.blocks.update({difficulty: 881321592344993}, {$set: {gas_used: 11, number_internal_transactions: 6}})

db.blocks.update({number_transactions: {$gt: 35}}, {$set: {block_height: 3923771}})

db.blocks.update({number_transactions: {$gt: 35}}, {$set: {block_height: 3923771}}, {multi: true})


update 方法有很多选项可供选择,可以参考官网的链接进行查看:https://docs.mongodb.com/manual/reference/method/db.collection.update/。这里演示其中一个选项:

db.customers.update({},{$set:{role:"citizen"}}, {multi:true})


更详细的请查看官方文档:https://docs.mongodb.com/manual/tutorial/query-documents/。

save

db.customers.save({"role":"villain", "name":"Jaws", "age":43})

db.customers.save({"_id":ObjectId("5891221756867ebff44cc889"),"role":"villain","name":"Goldfinger","age":77})

db.customers.save({"_id":ObjectId("5893888012acb8ada532a8e4"),"role":"villain","name":"PussyGalore","age":31})

文档删除

db.<collection name>.remove(<selection criteria>)
db.customers.remove({role:"admin"})
db.customers.remove({role:"villain"})

删除 1 条

db.customers.remove({role:"citizen"}, 1)

删除指定字段

db.customers.remove({role:"citizen"})

put documents back

db.customers.insert([{"role":"double-zero","name": "Bond","age": 32},{"role":"citizen","name": "Moneypenny","age":32},{"role":"citizen","name": "Q","age":67},{"role":"citizen","name": "M","age":57},{"role":"citizen","name": "Dr. No","age":52}])

删除所有

不加任何条件限制,将会删除所有。示例如下:

db.customers.remove({})

put documents back

db.customers.insert([{"role":"double-zero","name": "Bond","age": 32},{"role":"citizen","name": "Moneypenny","age":32},{"role":"citizen","name": "Q","age":67},{"role":"citizen","name": "M","age":57},{"role":"citizen","name": "Dr. No","age":52}])

projection

检索部分文档,如只检索某些字段。

# 查询的语法如下:
db.<collection name>.find(<selection criteria>,<list of fields with toggle 0 or 1>)

rs0:PRIMARY> db.orders.find({}, {_id: 0, cust_id: 1,})
{ "cust_id" : "A123" }
{ "cust_id" : "A123" }
{ "cust_id" : "B212" }
{ "cust_id" : "A123" }


_id 字段是默认显示的,如果不想显示,可以把该字段关闭,设置为 0 即可。如下:

rs0:PRIMARY> db.orders.find({}, {_id: 0, cust_id: 1, amount: 1})
{ "cust_id" : "A123", "amount" : 250 }
{ "cust_id" : "A123", "amount" : 500 }
{ "cust_id" : "B212", "amount" : 200 }
{ "cust_id" : "A123", "amount" : 300 }

rs0:PRIMARY> db.orders.find({amount: {$gt: 250}}, {_id: 0, cust_id: 1, amount: 1})
{ "cust_id" : "A123", "amount" : 500 }
{ "cust_id" : "A123", "amount" : 300 }

limit

限制返回的文档数。准备数据:

> use tyun
> db.crayons.insert([
    {
        "hex": "#EFDECD",
        "name": "Almond",
        "rgb": "(239, 222, 205)"
    },
    {
        "hex": "#CD9575",
        "name": "Antique Brass",
        "rgb": "(205, 149, 117)"
    },
    {
        "hex": "#FDD9B5",
        "name": "Apricot",
        "rgb": "(253, 217, 181)"
    },
    {
        "hex": "#78DBE2",
        "name": "Aquamarine",
        "rgb": "(120, 219, 226)"
    },
    {
        "hex": "#87A96B",
        "name": "Asparagus",
        "rgb": "(135, 169, 107)"
    },
    {
        "hex": "#FFA474",
        "name": "Atomic Tangerine",
        "rgb": "(255, 164, 116)"
    },
    {
        "hex": "#FAE7B5",
        "name": "Banana Mania",
        "rgb": "(250, 231, 181)"
    }
])


语法为:

db.<collection name>.find(<selection criteria>).limit(n)


接下来看具体的示例:

// 只输出 10 条文档
> db.crayons.find().limit(10)
{ "_id" : ObjectId("62de4227e3a734fa3d458bc1"), "hex" : "#EFDECD", "name" : "Almond", "rgb" : "(239, 222, 205)" }
{ "_id" : ObjectId("62de4227e3a734fa3d458bc2"), "hex" : "#CD9575", "name" : "Antique Brass", "rgb" : "(205, 149, 117)" }
{ "_id" : ObjectId("62de4227e3a734fa3d458bc3"), "hex" : "#FDD9B5", "name" : "Apricot", "rgb" : "(253, 217, 181)" }
{ "_id" : ObjectId("62de4227e3a734fa3d458bc4"), "hex" : "#78DBE2", "name" : "Aquamarine", "rgb" : "(120, 219, 226)" }
{ "_id" : ObjectId("62de4227e3a734fa3d458bc5"), "hex" : "#87A96B", "name" : "Asparagus", "rgb" : "(135, 169, 107)" }
{ "_id" : ObjectId("62de4227e3a734fa3d458bc6"), "hex" : "#FFA474", "name" : "Atomic Tangerine", "rgb" : "(255, 164, 116)" }
{ "_id" : ObjectId("62de4227e3a734fa3d458bc7"), "hex" : "#FAE7B5", "name" : "Banana Mania", "rgb" : "(250, 231, 181)" }

// 只查看 name 字段并且输出 10 条
> db.crayons.find({}, {"name": 1}).limit(10)
{ "_id" : ObjectId("62de4227e3a734fa3d458bc1"), "name" : "Almond" }
{ "_id" : ObjectId("62de4227e3a734fa3d458bc2"), "name" : "Antique Brass" }
{ "_id" : ObjectId("62de4227e3a734fa3d458bc3"), "name" : "Apricot" }
{ "_id" : ObjectId("62de4227e3a734fa3d458bc4"), "name" : "Aquamarine" }
{ "_id" : ObjectId("62de4227e3a734fa3d458bc5"), "name" : "Asparagus" }
{ "_id" : ObjectId("62de4227e3a734fa3d458bc6"), "name" : "Atomic Tangerine" }
{ "_id" : ObjectId("62de4227e3a734fa3d458bc7"), "name" : "Banana Mania" }

// 禁用 _id 字段,只显示 name 字段,并输出 10 条
> db.crayons.find({}, {_id: 0, name: 1}).limit(10)
{ "name" : "Almond" }
{ "name" : "Antique Brass" }
{ "name" : "Apricot" }
{ "name" : "Aquamarine" }
{ "name" : "Asparagus" }
{ "name" : "Atomic Tangerine" }
{ "name" : "Banana Mania" }

> db.crayons.find({}, {_id: 0}).limit(3)
{ "hex" : "#EFDECD", "name" : "Almond", "rgb" : "(239, 222, 205)" }
{ "hex" : "#CD9575", "name" : "Antique Brass", "rgb" : "(205, 149, 117)" }
{ "hex" : "#FDD9B5", "name" : "Apricot", "rgb" : "(253, 217, 181)" }

> db.crayons.find({hex: {$gt: "#777777"}}, {_id: 0, name: 1, age: 1}).limit(2)
{ "name" : "Almond" }
{ "name" : "Antique Brass" }

文档排序

在 MongoDB 中使用 sort() 方法对数据进行排序,sort() 方法可以通过参数指定排序的字段,并使用 1 和 -1 来指定排序的方式,其中 1 为升序排列,而 -1 是用于降序排列。文档排序的语法为:

db.<collection name>.find().sort({<field to sort on>:<1 for ascend, -1 descend>})


下面是具体的示例:

// 对 year 字段进行升序排序
> db.oscars.find().sort({"year":1}).pretty()
{
 "_id" : ObjectId("62de3de4457d1e8fd9a7a17a"),
 "year" : "1927",
 "title" : "Wings",
 "imdbId" : "tt0018578",
 "releaseDate" : "1927-05-19T05:00:00.000Z",
 "releaseCountry" : "USA",
 "releaseYear" : 1927,
 "releaseMonth" : 4,
 "releaseDay" : 19
}
{
 "_id" : ObjectId("62de3de4457d1e8fd9a7a17b"),
 "year" : "1929",
 "title" : "The Broadway Melody",
 "imdbId" : "tt0019729",
 "releaseDate" : "1929-02-01T05:00:00.000Z",
 "releaseCountry" : "USA",
 "releaseYear" : 1929,
 "releaseMonth" : 1,
 "releaseDay" : 1
}
{
 "_id" : ObjectId("62de3de4457d1e8fd9a7a17c"),
 "year" : "1930",
 "title" : "All Quiet on the Western Front",
 "imdbId" : "tt0020629",
 "releaseDate" : "1930-04-21T04:00:00.000Z",
 "releaseCountry" : "USA",
 "releaseYear" : 1930,
 "releaseMonth" : 3,
 "releaseDay" : 21
}
{
 "_id" : ObjectId("62de3de4457d1e8fd9a7a17d"),
 "year" : "1931",
 "title" : "Cimarron",
 "imdbId" : "tt0021746",
 "releaseDate" : "1931-01-26T05:00:00.000Z",
 "releaseCountry" : "USA",
 "releaseYear" : 1931,
 "releaseMonth" : 0,
 "releaseDay" : 26
}
{
 "_id" : ObjectId("62de3de4457d1e8fd9a7a17e"),
 "year" : "1932",
 "title" : "Grand Hotel",
 "imdbId" : "tt0022958",
 "releaseDate" : "1932-04-12T04:00:00.000Z",
 "releaseCountry" : "USA",
 "releaseYear" : 1932,
 "releaseMonth" : 3,
 "releaseDay" : 12
}
{
 "_id" : ObjectId("62de3de4457d1e8fd9a7a17f"),
 "year" : "1933",
 "title" : "Cavalcade",
 "imdbId" : "tt0023876",
 "releaseDate" : "1933-01-05T05:00:00.000Z",
 "releaseCountry" : "USA",
 "releaseYear" : 1933,
 "releaseMonth" : 0,
 "releaseDay" : 5
}
{
 "_id" : ObjectId("62de3de4457d1e8fd9a7a180"),
 "year" : "1934",
 "title" : "It Happened One Night",
 "imdbId" : "tt0025316",
 "releaseDate" : "1934-02-22T05:00:00.000Z",
 "releaseCountry" : "USA",
 "releaseYear" : 1934,
 "releaseMonth" : 1,
 "releaseDay" : 22
}
{
 "_id" : ObjectId("62de3de4457d1e8fd9a7a181"),
 "year" : "1935",
 "title" : "Mutiny on the Bounty",
 "imdbId" : "tt0026752",
 "releaseDate" : "1935-11-08T05:00:00.000Z",
 "releaseCountry" : "USA",
 "releaseYear" : 1935,
 "releaseMonth" : 10,
 "releaseDay" : 8
}
{
 "_id" : ObjectId("62de3de4457d1e8fd9a7a182"),
 "year" : "1936",
 "title" : "The Great Ziegfeld",
 "imdbId" : "tt0027698",
 "releaseDate" : "1936-03-22T04:00:00.000Z",
 "releaseCountry" : "USA",
 "releaseYear" : 1936,
 "releaseMonth" : 2,
 "releaseDay" : 22
}
{
 "_id" : ObjectId("62de3de4457d1e8fd9a7a183"),
 "year" : "1937",
 "title" : "The Life of Emile Zola",
 "imdbId" : "tt0029146",
 "releaseDate" : "1937-08-11T04:00:00.000Z",
 "releaseCountry" : "USA",
 "releaseYear" : 1937,
 "releaseMonth" : 7,
 "releaseDay" : 11
}
{
 "_id" : ObjectId("62de3de4457d1e8fd9a7a184"),
 "year" : "1938",
 "title" : "You Can't Take It with You",
 "imdbId" : "tt0030993",
 "releaseDate" : "1938-08-23T04:00:00.000Z",
 "releaseCountry" : "USA",
 "releaseYear" : 1938,
 "releaseMonth" : 7,
 "releaseDay" : 23
}
{
 "_id" : ObjectId("62de3de4457d1e8fd9a7a185"),
 "year" : "1939",
 "title" : "Gone with the Wind",
 "imdbId" : "tt0031381",
 "releaseDate" : "1939-12-28T05:00:00.000Z",
 "releaseCountry" : "USA",
 "releaseYear" : 1939,
 "releaseMonth" : 11,
 "releaseDay" : 28
}
{
 "_id" : ObjectId("62de3de4457d1e8fd9a7a186"),
 "year" : "1940",
 "title" : "Rebecca",
 "imdbId" : "tt0032976",
 "releaseDate" : "1940-03-27T04:00:00.000Z",
 "releaseCountry" : "USA",
 "releaseYear" : 1940,
 "releaseMonth" : 2,
 "releaseDay" : 27
}
{
 "_id" : ObjectId("62de3de4457d1e8fd9a7a187"),
 "year" : "1941",
 "title" : "How Green Was My Valley",
 "imdbId" : "tt0033729",
 "releaseDate" : "1941-10-28T05:00:00.000Z",
 "releaseCountry" : "USA",
 "releaseYear" : 1941,
 "releaseMonth" : 9,
 "releaseDay" : 28
}
{
 "_id" : ObjectId("62de3de4457d1e8fd9a7a188"),
 "year" : "1942",
 "title" : "Mrs. Miniver",
 "imdbId" : "tt0035093",
 "releaseDate" : "1942-07-22T04:00:00.000Z",
 "releaseCountry" : "USA",
 "releaseYear" : 1942,
 "releaseMonth" : 6,
 "releaseDay" : 22
}
{
 "_id" : ObjectId("62de3de4457d1e8fd9a7a189"),
 "year" : "1943",
 "title" : "Casablanca",
 "imdbId" : "tt0034583",
 "releaseDate" : "1942-11-26T05:00:00.000Z",
 "releaseCountry" : "USA",
 "releaseYear" : 1942,
 "releaseMonth" : 10,
 "releaseDay" : 26
}
{
 "_id" : ObjectId("62de3de4457d1e8fd9a7a18a"),
 "year" : "1944",
 "title" : "Going My Way",
 "imdbId" : "tt0036872",
 "releaseDate" : "1944-08-16T04:00:00.000Z",
 "releaseCountry" : "USA",
 "releaseYear" : 1944,
 "releaseMonth" : 7,
 "releaseDay" : 16
}
{
 "_id" : ObjectId("62de3de4457d1e8fd9a7a18b"),
 "year" : "1945",
 "title" : "The Lost Weekend",
 "imdbId" : "tt0037884",
 "releaseDate" : "1945-11-29T05:00:00.000Z",
 "releaseCountry" : "USA",
 "releaseYear" : 1945,
 "releaseMonth" : 10,
 "releaseDay" : 29
}
{
 "_id" : ObjectId("62de3de4457d1e8fd9a7a18c"),
 "year" : "1946",
 "title" : "The Best Years of Our Lives",
 "imdbId" : "tt0036868",
 "releaseDate" : "1946-12-25T05:00:00.000Z",
 "releaseCountry" : "USA",
 "releaseYear" : 1946,
 "releaseMonth" : 11,
 "releaseDay" : 25
}
{
 "_id" : ObjectId("62de3de4457d1e8fd9a7a18d"),
 "year" : "1947",
 "title" : "Gentleman's Agreement",
 "imdbId" : "tt0039416",
 "releaseDate" : "1947-11-11T05:00:00.000Z",
 "releaseCountry" : "USA",
 "releaseYear" : 1947,
 "releaseMonth" : 10,
 "releaseDay" : 11
}


title 字段进行升序排序:

// 只显示 year 及 title 字段,限制输出 10 条,并对 title 进行升序排序
> db.oscars.find({},{_id:0,year:1,title:1}).limit(10).sort({title:1})
{ "year" : "2001", "title" : "A Beautiful Mind" }
{ "year" : "1966", "title" : "A Man for All Seasons" }
{ "year" : "1950", "title" : "All About Eve" }
{ "year" : "1930", "title" : "All Quiet on the Western Front" }
{ "year" : "1949", "title" : "All the Kings Men" }
{ "year" : "1984", "title" : "Amadeus" }
{ "year" : "1999", "title" : "American Beauty" }
{ "year" : "1951", "title" : "An American in Paris" }
{ "year" : "1977", "title" : "Annie Hall" }
{ "year" : "2012", "title" : "Argo" }

// 该查询语句与上面的等价
> db.oscars.find({},{_id:0,year:1,title:1}).sort({title:1}).limit(10)

// 对 title 字段进行逆序排序
> db.oscars.find({},{_id:0,year:1,title:1}).limit(10).sort({title:-1})
{ "year" : "1938", "title" : "You Can't Take It with You" }
{ "year" : "1927", "title" : "Wings" }
{ "year" : "1961", "title" : "West Side Story" }
{ "year" : "1992", "title" : "Unforgiven" }
{ "year" : "1963", "title" : "Tom Jones" }
{ "year" : "1997", "title" : "Titanic" }
{ "year" : "1973", "title" : "The Sting" }
{ "year" : "1965", "title" : "The Sound of Music" }
{ "year" : "1991", "title" : "The Silence of the Lambs" }
{ "year" : "1945", "title" : "The Lost Weekend" }

// 查找 releaseYear 在 1970 后的文档,限制输出 10 条,并对 title 进行升序排序
> db.oscars.find({releaseYear:{$gt:1970}},{_id:0,year:1,title:1}).limit(10).sort({title:1})
{ "year" : "2001", "title" : "A Beautiful Mind" }
{ "year" : "1984", "title" : "Amadeus" }
{ "year" : "1999", "title" : "American Beauty" }
{ "year" : "1977", "title" : "Annie Hall" }
{ "year" : "2012", "title" : "Argo" }
{ "year" : "1995", "title" : "Braveheart" }
{ "year" : "1981", "title" : "Chariots of Fire" }
{ "year" : "2002", "title" : "Chicago" }
{ "year" : "2005", "title" : "Crash" }
{ "year" : "1990", "title" : "Dances With Wolves" }

索引相关

索引通常可以提供查询的效率。如果没有索引,MongoDB 在读取数据时需要扫描集合中每个文件并根据条件查询符合要求的文档。

创建索引的语法为

db.<collection name>.createIndex({<field to index>:<1 for ascend, -1 descend>})

创建索引

> db.oscars.createIndex({title:1})
{
 "createdCollectionAutomatically" : false,
 "numIndexesBefore" : 1,
 "numIndexesAfter" : 2,
 "ok" : 1
}

查看索引

> db.oscars.getIndexes()
[
 {
  "v" : 2,
  "key" : {
   "_id" : 1
  },
  "name" : "_id_"
 },
 {
  "v" : 2,
  "key" : {
   "title" : 1
  },
  "name" : "title_1"
 }
]

删除索引

// 查看当前有哪些索引
rs0:PRIMARY> db.oscars.getIndexes()
[
 {
  "v" : 2,
  "key" : {
   "_id" : 1
  },
  "name" : "_id_"
 },
 {
  "v" : 2,
  "key" : {
   "title" : 1
  },
  "name" : "title_1"
 }
]

// 删除名为 title_1 的索引
rs0:PRIMARY> db.oscars.dropIndex("title_1")
{
 "nIndexesWas" : 2,
 "ok" : 1,
 "$clusterTime" : {
  "clusterTime" : Timestamp(1667281131, 1),
  "signature" : {
   "hash" : BinData(0,"DuYoXmNI5MZSx0/pUYaLmHWyRw0="),
   "keyId" : NumberLong("7134969147229732868")
  }
 },
 "operationTime" : Timestamp(1667281131, 1)
}

// 删除所有索引,语法为:
db.col.dropIndexes()


关于索引的更多操作,可以参考官网文档:https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/#db.collection.createIndex。

聚合

类似 SQL 里的 GROUP BY,WHERE、JOIN 等功能。整个聚合运算过程称为管道(Pipeline),它由多个步骤(Stage)组成。管道做如下事情:


· 接受一些列文档(原始数据)

· 每个步骤对这些文档进行一些列运算

· 结果文档输出给下一个步骤

下表是 SQL 的命令与 MongoDB 聚合框架的对比:

自建 MongoDB 实战 | MongoDB 文档查询-鸿蒙开发者社区

聚合操作处理数据记录并返回计算结果。聚合操作将多个文档的值分组在一起,并且可以对分组数据执行各种操作以返回单个结果。MongoDB 提供了三种执行聚合的方法:聚合管道、映射还原函数和单一目的聚合方法。

rs0:PRIMARY> db.blocks.findOne()
{
 "_id" : ObjectId("62eb5e3c93f4f022d2b11d31"),
 "timestamp" : ISODate("2017-06-24T17:19:04Z"),
 "block_height" : 3923788,
 "number_transactions" : 28,
 "number_internal_transactions" : 4,
 "difficulty" : NumberLong("882071747513072"),
 "block_hash" : BinData(0,"MHg4OWQyMzVjNGUyZTRlNDk3ODQ0MGYzY2MxOTY2ZjFmZmIzNDNiOWI1Y2ZlYzllNWNlYmMzMzFmYjgxMGJkZWQz"),
 "gas_used" : 4694483
}

count()

如果我们要查询文档的数量,可以使用 count()

> db.oscars.count()
85

> db.oscars.find().count()
85

> db.oscars.find({year: "2012"}).count()
1

> db.oscars.find({$or: [{title: "hello tyun"}, {year:{$gt:"1989"}}]}).count()
23

distinct()

db.inventory.insert([
{ "_id": 1, "dept": "A", "item": { "sku": "111", "color": "red" }, "sizes": [ "S", "M" ] },
{ "_id": 2, "dept": "A", "item": { "sku": "111", "color": "blue" }, "sizes": [ "M", "L" ] },
{ "_id": 3, "dept": "B", "item": { "sku": "222", "color": "blue" }, "sizes": "S" },
{ "_id": 4, "dept": "A", "item": { "sku": "333", "color": "black" }, "sizes": [ "S" ] }
])


示例如下:

rs0:PRIMARY> db.inventory.distinct( "dept" )
[ "A", "B" ]

rs0:PRIMARY> db.inventory.distinct( "item.sku" )
[ "111", "222", "333" ]

rs0:PRIMARY> db.inventory.distinct( "sizes" )
[ "L", "M", "S" ]

下面给出几组 MQL 与 SQL 的对比,这样理解及记忆起来会更加深刻:

rs0:PRIMARY> db.persons.aggregate([
    {$match: {vocation: "ENGINEER"}},
    {$project: {
        "名字": '$firstname',
        "姓氏": '$lastname'
    }}
])
{
 "_id" : ObjectId("63048e2a938b950655d14470"),
 "名字" : "Sophie",
 "姓氏" : "Celements"
}
{
 "_id" : ObjectId("63048e2a938b950655d1446d"),
 "名字" : "Olive",
 "姓氏" : "Ranieri"
}
{
 "_id" : ObjectId("63048e2a938b950655d1446c"),
 "名字" : "Elise",
 "姓氏" : "Smith"
}
{
 "_id" : ObjectId("63048e2a938b950655d14471"),
 "名字" : "Carl",
 "姓氏" : "Simmons"
}

// 可以加入一个 $skip
rs0:PRIMARY> db.persons.aggregate([
    {$match: {vocation: "ENGINEER"}},
    {$skip: 1},
    {$project: {
        "名字": '$firstname',
        "姓氏": '$lastname'
    }}
])
{
 "_id" : ObjectId("63048e2a938b950655d1446d"),
 "名字" : "Olive",
 "姓氏" : "Ranieri"
}
{
 "_id" : ObjectId("63048e2a938b950655d1446c"),
 "名字" : "Elise",
 "姓氏" : "Smith"
}
{
 "_id" : ObjectId("63048e2a938b950655d14471"),
 "名字" : "Carl",
 "姓氏" : "Simmons"
}

rs0:PRIMARY> db.persons.aggregate([
    {$match: {vocation: "ENGINEER"}},
    {$skip: 1},
    {$limit :1},
    {$project: {
        "名字": '$firstname',
        "姓氏": '$lastname'
    }}
])
{ "_id" : ObjectId("63048e2a938b950655d1446d"), "名字" : "Olive", "姓氏" : "Ranieri" }


那么对应的 SQL 该怎么写呢?如下:

SELECT
  firstname AS "名字",
  lastname AS "姓氏"
FROM persions
WHERE vocation = "ENGINEER"
SKIP 1
LIMIT 1;


我们这里只给出这一个例子,对于其他的查询,我们应该可以轻松的实现。

聚合管道

聚合管道可以实现更复杂的查询。MongoDB 的聚合框架以数据处理管道的概念为模型。文档进入多步骤管道,将文档转换为聚合结果。最基本的管道步骤提供过滤器,就像查询和文档转换一样,修改文档输出的形式。

其他管道操作提供了按特定字段对文档进行分组和排序的工具,以及聚合数组内容的工具,包括文档数组。此外,管道步骤可以使用运算符来计算平均值或串联字符串等任务。

下面通过一个流程图来说明:

自建 MongoDB 实战 | MongoDB 文档查询-鸿蒙开发者社区

该管道分为 3 个步骤:

  • $match 步骤 – 通过 match 过滤我们需要的文档
  • $group 步骤 – 通过 group
  • $sort 步骤 – 对结果文档进行排序 (升序或降序)

db.<collection name>.aggregate([{<match, sort, geoNear>}, {<group>}])


MongoDB 中的聚合管道很类似 Unix 中的管道。

我们先看一个简单的例子:

> db.orders.insert([
    {"cust_id": "A123", "amount": 500, "status": "A"},
    {"cust_id": "A123", "amount": 250, "status": "A"},
    {"cust_id": "B212", "amount": 200, "status": "A"},
    {"cust_id": "A123", "amount": 300, "status": "D"}
])


我们针对订单状态为 "A" 的订单,对其进行一个分组聚合:

> db.orders.aggregate([
    {$match: {status: "A"}},
    {$group: {_id: "$cust_id", total: {$sum: "$amount"}}}
])

{ "_id" : "A123", "total" : 750 }
{ "_id" : "B212", "total" : 200 }

一个管道中的步骤可以写在一起,也可以分开写。如下图所示:

自建 MongoDB 实战 | MongoDB 文档查询-鸿蒙开发者社区

这里给出一个具体的示例:

var pipeline = [
  {"$unset": [
    "_id",
    "address",
  ]},    
    
  // Only match people born on or after 1st January 1970
  {"$match": {
    "dateofbirth": {"$gte": ISODate("1970-01-01T00:00:00Z")},
  }},
  
  /*
  {"$sort": {
    "dateofbirth": -1,
  }},      
    
  {"$limit": 2},  
  */
];


我们还可以把每个步骤分开写,最后放到一个列表里,这样看起来会更清晰。具体使用上面或下面这种形式,还是要看个人口味,没有绝对的好与坏。

var unsetStage = {
  "$unset": [
    "_id",
    "address",
  ]};    

var matchStage = {
  "$match": {
    "dateofbirth": {"$gte": ISODate("1970-01-01T00:00:00Z")},
  }};

var sortStage = {
   "$sort": {
    "dateofbirth": -1,
  }}; 


var limitStage = {"$limit": 2};
    
var pipeline = [
  unsetStage,
  matchStage,
  sortStage,
  limitStage,
];


接下来就准备一些演示用的文档。如下:

mongos> use test
switched to db test
mongos> // Create an index for a persons collection
mongos> db.persons.createIndex({"vocation": 1, "dateofbirth": 1});
{
 "raw" : {
  "shard1/mongo04.tyun.cn:27010,mongo05.tyun.cn:27010,mongo06.tyun.cn:27010" : {
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "commitQuorum" : "votingMembers",
   "ok" : 1
  }
 },
 "ok" : 1,
 "operationTime" : Timestamp(1660014410, 2),
 "$clusterTime" : {
  "clusterTime" : Timestamp(1660014410, 2),
  "signature" : {
   "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
   "keyId" : NumberLong(0)
  }
 }
}
mongos> // Insert records into the persons collection
mongos> db.persons.insertMany([
  {
    "person_id": "6392529400",
    "firstname": "Elise",
    "lastname": "Smith",
    "dateofbirth": ISODate("1972-01-13T09:32:07Z"),
    "vocation": "ENGINEER",
    "address": { 
        "number": 5625,
        "street": "Tipa Circle",
        "city": "Wojzinmoj",
    },
  },
  {
    "person_id": "1723338115",
    "firstname": "Olive",
    "lastname": "Ranieri",
    "dateofbirth": ISODate("1985-05-12T23:14:30Z"),    
    "gender": "FEMALE",
    "vocation": "ENGINEER",
    "address": {
        "number": 9303,
        "street": "Mele Circle",
        "city": "Tobihbo",
    },
  },
  {
    "person_id": "8732762874",
    "firstname": "Toni",
    "lastname": "Jones",
    "dateofbirth": ISODate("1991-11-23T16:53:56Z"),    
    "vocation": "POLITICIAN",
    "address": {
        "number": 1,
        "street": "High Street",
        "city": "Upper Abbeywoodington",
    },
  },
  {
    "person_id": "7363629563",
    "firstname": "Bert",
    "lastname": "Gooding",
    "dateofbirth": ISODate("1941-04-07T22:11:52Z"),    
    "vocation": "FLORIST",
    "address": {
        "number": 13,
        "street": "Upper Bold Road",
        "city": "Redringtonville",
    },
  },
  {
    "person_id": "1029648329",
    "firstname": "Sophie",
    "lastname": "Celements",
    "dateofbirth": ISODate("1959-07-06T17:35:45Z"),    
    "vocation": "ENGINEER",
    "address": {
        "number": 5,
        "street": "Innings Close",
        "city": "Basilbridge",
    },
  },
  {
    "person_id": "7363626383",
    "firstname": "Carl",
    "lastname": "Simmons",
    "dateofbirth": ISODate("1998-12-26T13:13:55Z"),    
    "vocation": "ENGINEER",
    "address": {
        "number": 187,
        "street": "Hillside Road",
        "city": "Kenningford",
    },
  },
]);
{
 "acknowledged" : true,
 "insertedIds" : [
  ObjectId("62f1cf57b611b4b0f16f8147"),
  ObjectId("62f1cf57b611b4b0f16f8148"),
  ObjectId("62f1cf57b611b4b0f16f8149"),
  ObjectId("62f1cf57b611b4b0f16f814a"),
  ObjectId("62f1cf57b611b4b0f16f814b"),
  ObjectId("62f1cf57b611b4b0f16f814c")
 ]
}
mongos> db.persons.find().pretty()
{
 "_id" : ObjectId("63048e2a938b950655d14470"),
 "person_id" : "1029648329",
 "firstname" : "Sophie",
 "lastname" : "Celements",
 "dateofbirth" : ISODate("1959-07-06T17:35:45Z"),
 "vocation" : "ENGINEER",
 "address" : {
  "number" : 5,
  "street" : "Innings Close",
  "city" : "Basilbridge"
 }
}
{
 "_id" : ObjectId("63048e2a938b950655d1446d"),
 "person_id" : "1723338115",
 "firstname" : "Olive",
 "lastname" : "Ranieri",
 "dateofbirth" : ISODate("1985-05-12T23:14:30Z"),
 "gender" : "FEMALE",
 "vocation" : "ENGINEER",
 "address" : {
  "number" : 9303,
  "street" : "Mele Circle",
  "city" : "Tobihbo"
 }
}
{
 "_id" : ObjectId("63048e2a938b950655d1446f"),
 "person_id" : "7363629563",
 "firstname" : "Bert",
 "lastname" : "Gooding",
 "dateofbirth" : ISODate("1941-04-07T22:11:52Z"),
 "vocation" : "FLORIST",
 "address" : {
  "number" : 13,
  "street" : "Upper Bold Road",
  "city" : "Redringtonville"
 }
}
{
 "_id" : ObjectId("63048e2a938b950655d1446c"),
 "person_id" : "6392529400",
 "firstname" : "Elise",
 "lastname" : "Smith",
 "dateofbirth" : ISODate("1972-01-13T09:32:07Z"),
 "vocation" : "ENGINEER",
 "address" : {
  "number" : 5625,
  "street" : "Tipa Circle",
  "city" : "Wojzinmoj"
 }
}
{
 "_id" : ObjectId("63048e2a938b950655d1446e"),
 "person_id" : "8732762874",
 "firstname" : "Toni",
 "lastname" : "Jones",
 "dateofbirth" : ISODate("1991-11-23T16:53:56Z"),
 "vocation" : "POLITICIAN",
 "address" : {
  "number" : 1,
  "street" : "High Street",
  "city" : "Upper Abbeywoodington"
 }
}
{
 "_id" : ObjectId("63048e2a938b950655d14471"),
 "person_id" : "7363626383",
 "firstname" : "Carl",
 "lastname" : "Simmons",
 "dateofbirth" : ISODate("1998-12-26T13:13:55Z"),
 "vocation" : "ENGINEER",
 "address" : {
  "number" : 187,
  "street" : "Hillside Road",
  "city" : "Kenningford"
 }
}
mongos> 
mongos> var pipeline = [
  // Match engineers only
  {"$match": {
    "vocation": "ENGINEER",
  }},
    
  // Sort by youngest person first
  {"$sort": {
    "dateofbirth": -1,
  }},      
    
  // Only include the first 3 youngest people
  {"$limit": 3},  

  // Exclude unrequired fields from each person record
  {"$unset": [
    "_id",
    "vocation",
    "address",
  ]},    
];
mongos> 
// 使用上面定义的管道进行查询
mongos> db.persons.aggregate(pipeline).pretty()
{
 "person_id" : "7363626383",
 "firstname" : "Carl",
 "lastname" : "Simmons",
 "dateofbirth" : ISODate("1998-12-26T13:13:55Z")
}
{
 "person_id" : "1723338115",
 "firstname" : "Olive",
 "lastname" : "Ranieri",
 "dateofbirth" : ISODate("1985-05-12T23:14:30Z"),
 "gender" : "FEMALE"
}
{
 "person_id" : "6392529400",
 "firstname" : "Elise",
 "lastname" : "Smith",
 "dateofbirth" : ISODate("1972-01-13T09:32:07Z")
}
mongos> db.persons.explain("executionStats").aggregate(pipeline);
{
 "serverInfo" : {
  "host" : "mongo01.tyun.cn",
  "port" : 27017,
  "version" : "4.4.15",
  "gitVersion" : "bc17cf2c788c5dda2801a090ea79da5ff7d5fac9"
 },
 "stages" : [
  {
   "$cursor" : {
    "queryPlanner" : {
     "plannerVersion" : 1,
     "namespace" : "test.persons",
     "indexFilterSet" : false,
     "parsedQuery" : {
      "vocation" : {
       "$eq" : "ENGINEER"
      }
     },
     "queryHash" : "967C3D4B",
     "planCacheKey" : "69A88B5C",
     "winningPlan" : {
      "stage" : "LIMIT",
      "limitAmount" : 3,
      "inputStage" : {
       "stage" : "FETCH",
       "inputStage" : {
        "stage" : "IXSCAN",
        "keyPattern" : {
         "vocation" : 1,
         "dateofbirth" : 1
        },
        "indexName" : "vocation_1_dateofbirth_1",
        "isMultiKey" : false,
        "multiKeyPaths" : {
         "vocation" : [ ],
         "dateofbirth" : [ ]
        },
        "isUnique" : false,
        "isSparse" : false,
        "isPartial" : false,
        "indexVersion" : 2,
        "direction" : "backward",
        "indexBounds" : {
         "vocation" : [
          "[\"ENGINEER\", \"ENGINEER\"]"
         ],
         "dateofbirth" : [
          "[MaxKey, MinKey]"
         ]
        }
       }
      }
     },
     "rejectedPlans" : [ ]
    },
    "executionStats" : {
     "executionSuccess" : true,
     "nReturned" : 3,
     "executionTimeMillis" : 0,
     "totalKeysExamined" : 3,
     "totalDocsExamined" : 3,
     "executionStages" : {
      "stage" : "LIMIT",
      "nReturned" : 3,
      "executionTimeMillisEstimate" : 0,
      "works" : 4,
      "advanced" : 3,
      "needTime" : 0,
      "needYield" : 0,
      "saveState" : 1,
      "restoreState" : 1,
      "isEOF" : 1,
      "limitAmount" : 3,
      "inputStage" : {
       "stage" : "FETCH",
       "nReturned" : 3,
       "executionTimeMillisEstimate" : 0,
       "works" : 3,
       "advanced" : 3,
       "needTime" : 0,
       "needYield" : 0,
       "saveState" : 1,
       "restoreState" : 1,
       "isEOF" : 0,
       "docsExamined" : 3,
       "alreadyHasObj" : 0,
       "inputStage" : {
        "stage" : "IXSCAN",
        "nReturned" : 3,
        "executionTimeMillisEstimate" : 0,
        "works" : 3,
        "advanced" : 3,
        "needTime" : 0,
        "needYield" : 0,
        "saveState" : 1,
        "restoreState" : 1,
        "isEOF" : 0,
        "keyPattern" : {
         "vocation" : 1,
         "dateofbirth" : 1
        },
        "indexName" : "vocation_1_dateofbirth_1",
        "isMultiKey" : false,
        "multiKeyPaths" : {
         "vocation" : [ ],
         "dateofbirth" : [ ]
        },
        "isUnique" : false,
        "isSparse" : false,
        "isPartial" : false,
        "indexVersion" : 2,
        "direction" : "backward",
        "indexBounds" : {
         "vocation" : [
          "[\"ENGINEER\", \"ENGINEER\"]"
         ],
         "dateofbirth" : [
          "[MaxKey, MinKey]"
         ]
        },
        "keysExamined" : 3,
        "seeks" : 1,
        "dupsTested" : 0,
        "dupsDropped" : 0
       }
      }
     }
    }
   },
   "nReturned" : NumberLong(3),
   "executionTimeMillisEstimate" : NumberLong(0)
  },
  {
   "$project" : {
    "_id" : false,
    "address" : false,
    "vocation" : false
   },
   "nReturned" : NumberLong(3),
   "executionTimeMillisEstimate" : NumberLong(0)
  }
 ],
 "ok" : 1,
 "operationTime" : Timestamp(1660014463, 1),
 "$clusterTime" : {
  "clusterTime" : Timestamp(1660014463, 1),
  "signature" : {
   "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
   "keyId" : NumberLong(0)
  }
 }
}
// 上面的管道查询也可以如下执行:
mongos> db.persons.find(
  {"vocation": "ENGINEER"},
  {"_id": 0, "vocation": 0, "address": 0},
).sort(
  {"dateofbirth": -1}
).limit(3).pretty()
{
 "person_id" : "7363626383",
 "firstname" : "Carl",
 "lastname" : "Simmons",
 "dateofbirth" : ISODate("1998-12-26T13:13:55Z")
}
{
 "person_id" : "1723338115",
 "firstname" : "Olive",
 "lastname" : "Ranieri",
 "dateofbirth" : ISODate("1985-05-12T23:14:30Z"),
 "gender" : "FEMALE"
}
{
 "person_id" : "6392529400",
 "firstname" : "Elise",
 "lastname" : "Smith",
 "dateofbirth" : ISODate("1972-01-13T09:32:07Z")
}

$bucket

根据指定的表达式和存储区边界将传入的文档分类为多个组,称为存储桶,并为每个存储桶输出一个文档。

场景:有一个名为 ​​oscars​​​ 的集合,我们要对该集合中电影的年代进行统计。如:处于 1920 ~ 1940 这个年代的有多少电影。这时就可以用到 ​​$bucket​​ 了,示例如下:

rs0:PRIMARY> db.oscars.aggregate(
[{
    $bucket: {
        groupBy: "$releaseYear", 
        boundaries: [1920, 1940, 1960, 1980, 2000, 2020], 
        default: "Other", 
        output: {
            "count": {$sum: 1}
        }
    }
}])
{ "_id" : 1920, "count" : 12 }
{ "_id" : 1940, "count" : 20 }
{ "_id" : 1960, "count" : 20 }
{ "_id" : 1980, "count" : 20 }
{ "_id" : 2000, "count" : 13 }

$unwind

用于把文档中的数组展开。示例如下:

rs0:PRIMARY> db.transactions.find({from: "Oraclize"}).limit(1).pretty()
{
 "_id" : ObjectId("6304843e285364eb2867480f"),
 "from" : "Oraclize",
 "to" : "0xece701c76bd00d1c3f96410a0c69ea8dfcf5f34e",
 "txhash" : "0x0a931fd5f5f38e0a1878fbbb81b00452e3822971de0b8f51ca8985e27a6a154e",
 "txfee" : 275994,
 "value" : 0,
 "block" : 3923794,
 "timestamp" : ISODate("2017-04-29T00:05:42Z"),
 "tags" : [
  "scam",
  "ico"
 ]
}


我们可以看到上述文档中包含了一个 tags 这样的一个数组,接下来我们要对其进行展开:

rs0:PRIMARY> db.transactions.aggregate([{$unwind: '$tags'}])
{ "_id" : ObjectId("6304843e285364eb28674806"), "from" : "ethfans.org", "to" : "0xa571e72f44964ec36c0b741b662802984c071f0a", "txhash" : "0x9ec440935666dac3f74690363926206b4cb53db2ef5a5100ecf84c53e84baa61", "txfee" : 651, "value" : 0.5011439, "block" : 3923794, "timestamp" : ISODate("2017-05-02T06:28:45Z"), "tags" : "scam" }
{ "_id" : ObjectId("6304843e285364eb28674817"), "from" : "0xe5b200c3babcd3a0b6e763de1a79c0b0743b37e8", "to" : "0x61ebb0a77fd6c64103f66de8b452914b3fb8ac45", "txhash" : "0x81cff6876077236583350a17928ca4224ceee49ae3e29cd5f673ffc1e102e354", "txfee" : 525, "value" : 0.025, "block" : 3923794, "timestamp" : ISODate("2017-04-12T00:53:26Z"), "tags" : "ico" }
{ "_id" : ObjectId("6304843e285364eb28674809"), "from" : "0x1151314c646ce4e0efd76d1af4760ae66a9fe30f", "to" : "0x479979d14a432c85d6464e265d331149a3a28955", "txhash" : "0x32d9e278666b96cf99762cffc91a1663d5cfcd6196123b2804f354e969920848", "txfee" : 1176, "value" : 40.2595, "block" : 3923794, "timestamp" : ISODate("2017-04-22T15:59:38Z"), "tags" : "ico" }
{ "_id" : ObjectId("6304843e285364eb2867480a"), "from" : "0x3c540be890df69eca5f0099bbedd5d667bd693f3", "to" : "0x4b9e0d224dabcc96191cace2d367a8d8b75c9c81", "txhash" : "0x527c477f867c6dfdae41800c012a5c175c82ea2ee21e659a9294bfd3d42d12cd", "txfee" : 28594, "value" : 0, "block" : 3923794, "timestamp" : ISODate("2017-05-22T04:21:03Z"), "tags" : "ico" }
{ "_id" : ObjectId("6304843e285364eb2867480c"), "from" : "0x0489c9837f5a7fc08a1e6475f405071ed2c57932", "to" : "0x6090a6e47849629b7245dfa1ca21d94cd15878ef", "txhash" : "0x6bad2be5753870e725a2fbc88af023bd601634485f1192fdb2de293f5075e547", "txfee" : 189846, "value" : 0, "block" : 3923794, "timestamp" : ISODate("2017-04-02T11:00:55Z"), "tags" : "scam" }
{ "_id" : ObjectId("6304843e285364eb2867480d"), "from" : "0x9251d5835f4a68d1e3603735b43409941c244343", "to" : "0x6090a6e47849629b7245dfa1ca21d94cd15878ef", "txhash" : "0x6e6ba47c0eff5dedf8bb9721e60cf6a95684f1adc98eb732e36b61a071736c95", "txfee" : 199838, "value" : 0, "block" : 3923794, "timestamp" : ISODate("2017-02-21T12:19:31Z"), "tags" : "scam" }
{ "_id" : ObjectId("6304843e285364eb28674811"), "from" : "0x54a02575a8ee224cc8504ebac557b84d4c8613a0", "to" : "0x6090a6e47849629b7245dfa1ca21d94cd15878ef", "txhash" : "0xadeabd3567b84e04164d4bbbdb675d240010606c7fe18a47b44af21b57fb75b2", "txfee" : 960369, "value" : 0.01, "block" : 3923794, "timestamp" : ISODate("2017-03-20T09:30:01Z"), "tags" : "scam" }
{ "_id" : ObjectId("6304843e285364eb28674811"), "from" : "0x54a02575a8ee224cc8504ebac557b84d4c8613a0", "to" : "0x6090a6e47849629b7245dfa1ca21d94cd15878ef", "txhash" : "0xadeabd3567b84e04164d4bbbdb675d240010606c7fe18a47b44af21b57fb75b2", "txfee" : 960369, "value" : 0.01, "block" : 3923794, "timestamp" : ISODate("2017-03-20T09:30:01Z"), "tags" : "ico" }
{ "_id" : ObjectId("6304843e285364eb28674813"), "from" : "0xcdfc3e6c0c91c6ed7a124c4d18429888201e0675", "to" : "0x69c6d9f7116f0d5c103d20ffeee1ef7224be2a78", "txhash" : "0x78d1d9b9c7739986b1e321806d7e1da6019d1181f560effa1f2244ae43ce2c02", "txfee" : 441, "value" : 0.2, "block" : 3923794, "timestamp" : ISODate("2017-03-18T23:13:25Z"), "tags" : "ico" }
{ "_id" : ObjectId("6304843e285364eb28674818"), "from" : "0x7b796cac3899702794bb711d3ec2dc1b24d66007", "to" : "0x667088b212ce3d06a1b553a7221e1fd19000d9af", "txhash" : "0xab6ae0b6724802b3b380388afa75f52403bcb64a9feee0df9fd3a7c3651f891a", "txfee" : 112083, "value" : 0, "block" : 3923794, "timestamp" : ISODate("2017-02-02T07:53:05Z"), "tags" : "ico" }
{ "_id" : ObjectId("6304843e285364eb2867481a"), "from" : "0x0ac2733281597ccb339db01d399752464e7fca55", "to" : "0x1c3f580daeaac2f540c998c8ae3e4b18440f7c45", "txhash" : "0xf8eec318fdfc404380d8ee1673aa09d10c6b428f1a6991168f32ccb0453e2dd2", "txfee" : 651, "value" : 1.02828387, "block" : 3923794, "timestamp" : ISODate("2017-05-17T07:36:40Z"), "tags" : "scam" }
{ "_id" : ObjectId("6304843e285364eb2867481a"), "from" : "0x0ac2733281597ccb339db01d399752464e7fca55", "to" : "0x1c3f580daeaac2f540c998c8ae3e4b18440f7c45", "txhash" : "0xf8eec318fdfc404380d8ee1673aa09d10c6b428f1a6991168f32ccb0453e2dd2", "txfee" : 651, "value" : 1.02828387, "block" : 3923794, "timestamp" : ISODate("2017-05-17T07:36:40Z"), "tags" : "ico" }
{ "_id" : ObjectId("6304843e285364eb28674819"), "from" : "0x6ae429d8da420531f584fd6d0798fd3672ee0b46", "to" : "0x1c3f580daeaac2f540c998c8ae3e4b18440f7c45", "txhash" : "0xfb3a43f8dbb92d5e2ea8608cbcaf483ef6a4070a89b9d3f8dc8125ea1c834236", "txfee" : 651, "value" : 1.48888387, "block" : 3923794, "timestamp" : ISODate("2017-03-11T08:45:27Z"), "tags" : "ico" }
{ "_id" : ObjectId("6304843e285364eb28674807"), "from" : "BTC-e", "to" : "0xda6e1264457f239aff400bb4ad86b6e1a7fe0c7b", "txhash" : "0x0c34837b6dcaa8700aed50cee4ca89a186b106ab0e3e262e2a696213ead8f4eb", "txfee" : 651, "value" : 0.07418323, "block" : 3923794, "timestamp" : ISODate("2017-06-22T09:24:15Z"), "tags" : "scam" }
{ "_id" : ObjectId("6304843e285364eb28674808"), "from" : "Bittrex", "to" : "0xf594ba392c4d9b35e93ee74ba18cb1958f0128ac", "txhash" : "0xab86b9c6a96b51de0325882bd95f70295b8d0ec9042e3feeacf4ac99eae63df6", "txfee" : 1071, "value" : 0.253256, "block" : 3923794, "timestamp" : ISODate("2017-04-17T17:05:21Z"), "tags" : "scam" }
{ "_id" : ObjectId("6304843e285364eb28674812"), "from" : "0x9771d581ff85ea108652346bff89f45b3bfd2bc9", "to" : "0x6090a6e47849629b7245dfa1ca21d94cd15878ef", "txhash" : "0x884194effc5f0b675e932f110d8d270ecf0ed7e4643ba97d42880e8165153306", "txfee" : 878715, "value" : 2.56, "block" : 3923794, "timestamp" : ISODate("2017-06-07T10:47:05Z"), "tags" : "scam" }
{ "_id" : ObjectId("6304843e285364eb28674812"), "from" : "0x9771d581ff85ea108652346bff89f45b3bfd2bc9", "to" : "0x6090a6e47849629b7245dfa1ca21d94cd15878ef", "txhash" : "0x884194effc5f0b675e932f110d8d270ecf0ed7e4643ba97d42880e8165153306", "txfee" : 878715, "value" : 2.56, "block" : 3923794, "timestamp" : ISODate("2017-06-07T10:47:05Z"), "tags" : "ico" }
{ "_id" : ObjectId("6304843e285364eb2867480b"), "from" : "0x11d22d5f945dc8aff2b1844ba587dae211ea95a6", "to" : "0x1a95b271b0535d15fa49932daba31ba612b52946", "txhash" : "0x5a7c451d22948aa098791470116f82d0591498cd329c150edfc4cbfa0f926520", "txfee" : 7451, "value" : 0, "block" : 3923794, "timestamp" : ISODate("2017-06-04T04:42:45Z"), "tags" : "scam" }
{ "_id" : ObjectId("6304843e285364eb2867480e"), "from" : "DwarfPool1", "to" : "0xda2b18cb269540d729c4ecab541a095cf265f5d3", "txhash" : "0x0dbaeb0e494016483cf537b937be2679c8c9fc3c75c55968396fed45dc6d64a9", "txfee" : 42, "value" : 0.23463116, "block" : 3923794, "timestamp" : ISODate("2017-03-09T09:33:17Z"), "tags" : "ico" }
{ "_id" : ObjectId("6304843e285364eb2867480f"), "from" : "Oraclize", "to" : "0xece701c76bd00d1c3f96410a0c69ea8dfcf5f34e", "txhash" : "0x0a931fd5f5f38e0a1878fbbb81b00452e3822971de0b8f51ca8985e27a6a154e", "txfee" : 275994, "value" : 0, "block" : 3923794, "timestamp" : ISODate("2017-04-29T00:05:42Z"), "tags" : "scam" }

用户相关操作

创建 admin 超级用户

use admin
db.createUser(
  {
    user: "tyun",
    pwd: "xxxxxxxxxx",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)


大家可以参考这个链接 https://docs.mongodb.com/manual/reference/built-in-roles/ 查看 MongoDB 内置的角色。如果不清楚有哪些内置的角色,可以使用命令节能型查看:

rs0:PRIMARY> show roles
{
 "role" : "dbAdmin",
 "db" : "test",
 "isBuiltin" : true,
 "roles" : [ ],
 "inheritedRoles" : [ ]
}
{
 "role" : "dbOwner",
 "db" : "test",
 "isBuiltin" : true,
 "roles" : [ ],
 "inheritedRoles" : [ ]
}
{
 "role" : "enableSharding",
 "db" : "test",
 "isBuiltin" : true,
 "roles" : [ ],
 "inheritedRoles" : [ ]
}
{
 "role" : "read",
 "db" : "test",
 "isBuiltin" : true,
 "roles" : [ ],
 "inheritedRoles" : [ ]
}
{
 "role" : "readWrite",
 "db" : "test",
 "isBuiltin" : true,
 "roles" : [ ],
 "inheritedRoles" : [ ]
}
{
 "role" : "userAdmin",
 "db" : "test",
 "isBuiltin" : true,
 "roles" : [ ],
 "inheritedRoles" : [ ]
}


我们这里介绍一下 root 权限。其中 root 角色包含下面几个角色:

readWriteAnyDatabase

dbAdminAnyDatabase

userAdminAnyDatabase

clusterAdmin

restore

backup

查看当前用户

rs0:PRIMARY> db.runCommand({connectionStatus : 1})
{
 "authInfo" : {
  "authenticatedUsers" : [
   {
    "user" : "root",
    "db" : "admin"
   }
  ],
  "authenticatedUserRoles" : [
   {
    "role" : "root",
    "db" : "admin"
   }
  ]
 },
 "ok" : 1,
 "$clusterTime" : {
  "clusterTime" : Timestamp(1667270694, 1),
  "signature" : {
   "hash" : BinData(0,"YqsIxUZqShsB3Rq6YMf447Rp+DM="),
   "keyId" : NumberLong("7134969147229732868")
  }
 },
 "operationTime" : Timestamp(1667270694, 1)
}

创建常规用户

接下来创建的用户 test 对 db store 具有读写权限。操作如下:

`db.createUser(
  {
    user: "test",
    pwd: "xxxxxxxx",
    roles: [ { role: "readWrite", db: "store" } ]
  }
)`

删除用户

db.dropUser("<user name>")

Pymongo 使用

阿里云的 MongoDB,需要使用使用 3.0 版本以上的客户端才能连接成功,否则会出现鉴权失败,登录时请使用管理员账户进行登录。接着安装 pymongo,

pip install pymongo


基本的登录代码如下:

# py2.7 版本

# -*- coding: utf-8 -*-

import urllib
import pymongo

address = "dds-ccccccc.mongodb.rds.aliyuncs.com:3717/"
username = urllib.quote_plus('root')
password = urllib.quote_plus('xxxxxxxxxxxxxxxxx')
mongo_uri = "mongodb://{0}:{1}@{2}".format(username, 
                                           password, 
                                           address)
database = 'xxxxxxx'

myclient = pymongo.MongoClient(mongo_uri)

# dblist = myclient.list_database_names()
demo_db = myclient[database]

for collection in demo_db.list_collection_names():
    collection.delete_many({})
再看一个简单的代码片段,

from pymongo import MongoClient
from pprint import pprint

uri = "mongodb://127.0.0.1:27017/"
client = MongoClient(uri)
pprint(client)


db = client["eshop"]
user_coll = db["users"]

new_user = {
 "username": "nina",
 "password": "xxxx",
 "email": "123456@qq.com"
}
result = user_coll.insert_one(new_user)
pprint(result)

result = user_coll.find_one()
pprint(result)

result = user_coll.update_one({
    "username": "nina"
}, {
    "$set": {
        "phone": "123456789"
    }
})

result = user_coll.find_one({ "username": "nina" })
pprint(result)


client.close()


创建 mongod 实例

为了在实验中使用 MongoDB,我们先启动一个临时 mongod 实例:

mongod --dbpath /data --port 27017


以上指令将使用 /data 作为数据目录(如果不存在请创建),在默认端口 27017 启动一个临时 mongod 实例。

安装 MongoDB 驱动

在使用 MongoDB 之前必须先安装用于访问数据库的驱动程序。这里我们以 Python 为例给大家演示:

pip install pymongo

检查驱动

在 python 交互模式下导入 pymongo,检查驱动是否已正确安装:

import pymongo
pymongo.version
# 结果:
# '3.7.2'

使用驱动连接 MongoDB

使用驱动连接到 MongoDB 集群只需要指定 MongoDB 连接字符串即可。其基本格式可以参考文档: Connection String URI Format

  • 标准的连接字符串:mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]
  • 复制集的连接字符串:mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/?replicaSet=myRepl
  • 分片集的连接字符串:mongodb://mongos0.example.com:27017,mongos1.example.com:27017,mongos2.example.com:27017


连接字符串的大部分参数在不同编程语言之间是通用的。本实验中,我们使用以下连接字符串

uri = "mongodb://127.0.0.1:27017/?minPoolSize=10&maxPoolSize=100"


这里指定了连接池保持连接的最小数量是 10,最大连接数 100。要连接到 MongoDB,在 Python 交互模式下执行以下语句即可:

from pymongo import MongoClient

uri = "mongodb://127.0.0.1:27017/?minPoolSize=10&maxPoolSize=100"
client = MongoClient(uri)
print client
# 结果:
# MongoClient(host=['127.0.0.1:27017'], document_class=dict, tz_aware=False, connect=True, minpoolsize=10, maxpoolsize=100)

执行 CRUD 操作

在上述过程中创建MongoClient后,我们将使用它来完成CRUD操作。假设我们将使用foo数据库的bar集合来完成测试:

test_db = client["foo"]
bar_coll = test_db["bar"]
result = bar_coll.insert_one({
    "string": "Hello World"
})
print result
# 结果:
# <pymongo.results.InsertOneResult object at 0x1054ebab8>


我们将结果查询出来看看是否正确:

result = bar_coll.find_one({
    "string": "Hello World"
})
print result
# 结果:
# {u'_id': ObjectId('5dbeb2290f08fbb017e0e583'), u'string': u'Hello World'}


我们可以注意到这个对象上添加了一个_id,它是MongoDB对每个对象赋予的唯一主键,如果没有指定则由系统自动分配一个ObjectId来填充。

现在我们尝试对刚才的文档进行一点修改,然后再查询它:

result = bar_coll.update_one({
    "string": "Hello World"
}, {
    "$set": {
        "from": "Tom the cat"
    }
})
result = bar_coll.find_one({
    "string": "Hello World"
})
print result
# 结果:
# {u'_id': ObjectId('5dbeb2290f08fbb017e0e583'), u'from': u'Tom the cat', u'string': u'Hello World'}


最后我们​​将它从表中删除:

result = bar_coll.delete_one({
    "string": "Hello World"
})
print result
# 结果:
# <pymongo.results.DeleteResult object at 0x105501440>

非交互模式下执行

除了在 Python 交互模式下执行,我们当然也可以将代码放在一个文件中执行。把等价的代码放到文件中:

# hello_world.py
from pymongo import MongoClient

uri = "mongodb://127.0.0.1:27017/?minPoolSize=10&maxPoolSize=100"
client = MongoClient(uri)
print client

test_db = client["foo"]
bar_coll = test_db["bar"]
result = bar_coll.insert_one({
    "string": "Hello World"
})
print result

result = bar_coll.find_one({
    "string": "Hello World"
})
print result

result = bar_coll.update_one({
    "string": "Hello World"
}, {
    "$set": {
        "from": "Tom the cat"
    }
})
result = bar_coll.find_one({
    "string": "Hello World"
})
print result

result = bar_coll.delete_one({
    "string": "Hello World"
})
print result

client.close()


执行这个文件:

$ python hello_world.py


我们将得到跟之前相同的结果。接下来我们使用 Python 代码演示聚合查询:

(venv36) [root@mongo01 ~]# cat block_aggregations.py 

from pymongo import MongoClient
from bson.son import SON
import pprint

class BlockAggregation:
    def __init__(self):
        client = MongoClient()
        db = client.test
        self.collection = db.blocks

    def average_number_transactions_total_block(self):
        pipeline = [
            {"$group": {"_id": "average_transactions_per_block", "count": {"$avg": "$number_transactions"}}},
        ]
        result = self.collection.aggregate(pipeline)
        for res in result:
            print(res)

    def average_number_transactions_internal_block(self):
        pipeline = [
            {"$group": {"_id": "average_transactions_internal_per_block", "count": {"$avg": "$number_internal_transactions"}}},
        ]
        result = self.collection.aggregate(pipeline)
        for res in result:
            print(res)

    def average_gas_block(self):
        pipeline = [
            {"$group": {"_id": "average_gas_used_per_block",
                        "count": {"$avg": "$gas_used"}}},
        ]
        result = self.collection.aggregate(pipeline)
        for res in result:
            print(res)

    def average_difficulty_block(self):
        pipeline = [
            {"$group": {"_id": "average_difficulty_per_block",
                        "count": {"$avg": "$difficulty"}, "stddev": {"$stdDevPop": "$difficulty"}}},
        ]
        result = self.collection.aggregate(pipeline)
        for res in result:
            print(res)

    def top_ten_addresses_to(self):
        pipeline = [
            {"$group": {"_id": "$to", "count": {"$sum": 1}}},
            {"$sort": SON([("count", -1)])},
            {"$limit": 10},
        ]
        result = self.collection.aggregate(pipeline)
        for res in result:
            print(res)

    def average_value_per_transaction(self):
        pipeline = [
            {"$group": {"_id": "value", "averageValues": {"$avg": "$value"}, "stdDevValues": {"$stdDevPop": "$value"}}},
        ]
        result = self.collection.aggregate(pipeline)
        for res in result:
            print(res)

    def average_fee_per_transaction(self):
        pipeline = [
            {"$group": {"_id": "value", "averageFees": {"$avg": "$txfee"}, "stdDevValues": {"$stdDevPop": "$txfee"}}},
        ]
        result = self.collection.aggregate(pipeline)
        for res in result:
            print(res)

    def active_hour_of_day_transactions(self):
        pipeline = [
            {"$group": {"_id": {"$hour": "$timestamp"}, "transactions": {"$sum": 1}}},
            {"$sort": SON([("transactions", -1)])},
            {"$limit": 1},
        ]
        result = self.collection.aggregate(pipeline)
        for res in result:
            print(res)

    def active_hour_of_day_values(self):
        pipeline = [
            {"$group": {"_id": {"$hour": "$timestamp"}, "transaction_values": {"$sum": "$value"}}},
            {"$sort": SON([("transactions", -1)])},
            {"$limit": 1},
        ]
        result = self.collection.aggregate(pipeline)
        for res in result:
            print(res)

    def active_day_of_week_transactions(self):
        pipeline = [
            {"$group": {"_id": {"$dayOfWeek": "$timestamp"}, "transactions": {"$sum": 1}}},
            {"$sort": SON([("transactions", -1)])},
            {"$limit": 1},
        ]
        result = self.collection.aggregate(pipeline)
        for res in result:
            print(res)

    def active_day_of_week_values(self):
        pipeline = [
            {"$group": {"_id": {"$dayOfWeek": "$timestamp"}, "transaction_values": {"$sum": "$value"}}},
            {"$sort": SON([("transactions", -1)])},
            {"$limit": 1},
        ]
        result = self.collection.aggregate(pipeline)
        for res in result:
            print(res)


def main():
    # 1. Average number of transactions per block, both in total and also in contract internal transactions
    BlockAggregation().average_number_transactions_total_block()
    BlockAggregation().average_number_transactions_internal_block()

    # 2. Average gas used per block
    BlockAggregation().average_gas_block()

    # 3. Average gas used per transaction in a block, is there a “window of opportunity” to submit my smart contract in a block?

    # 4. Average difficulty per block and how it deviates
    BlockAggregation().average_difficulty_block()

    # 5. top addresses to
    BlockAggregation().top_ten_addresses_to()

    # 6. Average value per transaction
    BlockAggregation().average_value_per_transaction()

    # 7. Average fee per transaction
    BlockAggregation().average_fee_per_transaction()

    # 8. Most Active hour of day (1:Monday, 7: Sunday)
    BlockAggregation().active_hour_of_day_transactions()
    BlockAggregation().active_hour_of_day_values()

    # 9. Most active day of week (1:Monday, 7: Sunday)
    BlockAggregation().active_day_of_week_transactions()
    BlockAggregation().active_day_of_week_values()


if __name__ == '__main__':
    main()


执行上述代码:

(venv36) [root@mongo01 chapter_6]# python block_aggregations.py 
1. Average number of transactions per block, both in total and also in contract internal transactions
{'_id': 'average_transactions_per_block', 'count': 39.458333333333336}
{'_id': 'average_transactions_internal_per_block', 'count': 8.0}

2. Average gas used per block
{'_id': 'average_gas_used_per_block', 'count': 2563647.9166666665}

4. Average difficulty per block and how it deviates
{'_id': 'average_difficulty_per_block', 'count': 881676386932100.0, 'stddev': 446694674991.6385}

5. top addresses to
{'_id': None, 'count': 24}

6. Average value per transaction
{'_id': 'value', 'averageValues': None, 'stdDevValues': None}

7. Average fee per transaction
{'_id': 'value', 'averageFees': None, 'stdDevValues': None}

8. Most Active hour of day (1:Monday, 7: Sunday
{'_id': 17, 'transactions': 24}
{'_id': 17, 'transaction_values': 0}

9. Most active day of week (1:Monday, 7: Sunday)
{'_id': 7, 'transactions': 24}
{'_id': 7, 'transaction_values': 0}

总结

本篇我们介绍了 MongoDB 常用的文档查询相关内容。此篇涉及的内容较多,需要多动手实践,方能记忆深刻。我们可以结合前篇文章中关于 SQL 及 MongoDB 的对照表进行对比着学习,这里再次列出来供参考。如下:

自建 MongoDB 实战 | MongoDB 文档查询-鸿蒙开发者社区


文章转载自公众号:新钛云服

分类
标签
已于2023-7-10 16:08:47修改
收藏
回复
举报
回复
    相关推荐