https://docs.mongodb.com/manual/tutorial/insert-documents/html
db.questions.insert( { "_id":"003", "title":"第三個問題", "view":0, "isDeleted":false, "content":"第三個問題", "status":"open", "tags":["c#"], "answers":[ {"content":"回答1"}, {"content":"回答2"}, {"content":"回答3"} ] } )
db.questions.insertMany( [ { "_id":"004", "title":"第三個問題", "view":0, "isDeleted":false, "content":"第三個問題", "status":"open", "tags":["c#"], "answers":[ {"content":"回答1"}, {"content":"回答2"}, {"content":"回答3"} ] }, { "_id":"005", "title":"第三個問題", "view":0, "isDeleted":false, "content":"第三個問題", "status":"open", "tags":["c#"], "answers":[ {"content":"回答1"}, {"content":"回答2"}, {"content":"回答3"} ] } ] )
https://docs.mongodb.com/manual/reference/operator/query/mongodb
db.users.find( { age: { $gt: 18 } }, // 查詢條件 { name: 1, address: 1 } // 查詢字段 ).limit(5)
db.getCollection('questions').find({"title":"第三個問題"},{"title":1,"content":1}) db.getCollection('questions').find({},{"title":1,"content":1}).skip(1).limit(2)
Name | Description |
---|---|
$eq | 等於 |
$gt | 大於 |
$gte | 大於等於 |
$lt | 小於 |
$lte | 小於等於 |
$ne | 不等於 |
$in | 存在於 |
$nin | 不存在於:通常用於數組 |
// 大於等於 db.getCollection('questions').find({"view":{$gte: NumberInt(0)}}) // 存在於 db.getCollection('questions').find({"tags":{$in: ["c#"]}})
Name | Description |
---|---|
$and | 知足多個條件 |
$or | 知足多個條件中的一個 |
$not | 不匹配,或者字段不存在 |
$nor | 多個條件,一個都不知足 |
// 知足多個條件中的一個 db.getCollection('questions').find({$or: [ {"tags":{$in: ["c#"]}}, {"view":{$gt:2}} ] }) db.getCollection('questions').find({"view":{"$gt": 5}}) // 不匹配,或者字段不存在(取反) db.getCollection('questions').find({"view": {$not: {"$gt": 5}}}) // 多個條件,一個都不知足 db.getCollection('questions').find({$nor: [{"view":{"$gt": 5}}]})
Name | Description |
---|---|
$exists | 存在某個字段 |
$type | 字段的類型 |
// 存在某個字段則顯示 db.getCollection('questions').find({"best": {$exists:1}}) // 不存在某個字段則顯示 db.getCollection('questions').find({"best": {$exists:0}}) // 字段的類型,16表明32-byte integer db.getCollection('questions').find({"view": {$type: 16}})
https://mongoing.com/docs/reference/bson-types.htmlshell
db.getCollection('questions').find({"best.content":{$eq: "最好的答案"}})
Name | Description |
---|---|
$all | 全部元素匹配,匹配簡單類型數組 |
$elemMatch | 用於匹配 object 數組 |
$size | 長度條件 |
db.getCollection('questions').find({"tags": {$in: ["c#"]}}) db.getCollection('questions').find({"tags": {$nin: ["c#"]}}) // 都必須包含 db.getCollection('questions').find({"tags": {$all: ["c#", "asp.net core"]}}) // 大小爲2 db.getCollection('questions').find // 包含 回答1 的數組 db.getCollection('questions').find({"answers": {$elemMatch: {"content": "回答1"}}}) db.getCollection('questions').find({"answers": {$elemMatch: {"content": {$gte: "回答1"}}}})
只在 mongo shell 中有效,其餘語言版本 sdk 無效c#
本做品採用知識共享署名-非商業性使用-相同方式共享 4.0 國際許可協議進行許可。數組
歡迎轉載、使用、從新發布,但務必保留文章署名 鄭子銘 (包含連接: http://www.cnblogs.com/MingsonZheng/ ),不得用於商業目的,基於本文修改後的做品務必以相同的許可發佈。asp.net
若有任何疑問,請與我聯繫 (MingsonZheng@outlook.com) 。.net