mangoDB的Collection操作

MongoDB中的集合是一组文档的集,相当于关系型数据库中的表。

0、前期准备

链接MongoDB

> show tables;
> show databases;
admin   0.000GB
app     0.000GB
config  0.000GB
local   0.000GB
> use app
switched to db app
> show tables;
test
> db.test.find()
{ "_id" : ObjectId("613c7060f832314229fba0dd"), "name" : "sunyhua" }
{ "_id" : ObjectId("613d669e21ebb2c51ece4697"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66cd21ebb2c51ece4698"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66df21ebb2c51ece4699"), "name" : "sunyuhua111" }
{ "_id" : ObjectId("613d6e82dbe8e0b55ca50709"), "name" : "zhangsanfeng" }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070a"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070b"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070c"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
{ "_id" : ObjectId("613d70efdbe8e0b55ca5070d"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
{ "_id" : ObjectId("613d710edbe8e0b55ca5070e"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
{ "_id" : ObjectId("613d7174dbe8e0b55ca5070f"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca50710"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca50711"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50712"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50713"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50714"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
>

1、创建集合

MongoDB使用db.createCollection()函数来创建集合。
语法格式:db.createCollection(name, options)。
name: 要创建的集合名称。
options: 可选参数, 指定有关内存大小及索引的选项。
在MongoDB中,我们也可以不用创建集合,当我们插入一些数据时,会自动创建集合,并且会使用文档管理命令中的集合名称作为集合的名称。文档管理命令后续课程详解。
向库中插入一条数据

db.test.insert({"name":"zhangsanfeng"})
> show dbs;
admin   0.000GB
app     0.000GB
config  0.000GB
local   0.000GB
> use app
switched to db app
> show tables;
test
> db.test.find()
{ "_id" : ObjectId("613c7060f832314229fba0dd"), "name" : "sunyhua" }
{ "_id" : ObjectId("613d669e21ebb2c51ece4697"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66cd21ebb2c51ece4698"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66df21ebb2c51ece4699"), "name" : "sunyuhua111" }
> db.test.insert({"name":"zhangsanfeng"})
WriteResult({ "nInserted" : 1 })
> db.test.find()
{ "_id" : ObjectId("613c7060f832314229fba0dd"), "name" : "sunyhua" }
{ "_id" : ObjectId("613d669e21ebb2c51ece4697"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66cd21ebb2c51ece4698"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66df21ebb2c51ece4699"), "name" : "sunyuhua111" }
{ "_id" : ObjectId("613d6e82dbe8e0b55ca50709"), "name" : "zhangsanfeng" }
>

2.查看集合详情

db.test.stats()
> db.test.stats()
{
        "ns" : "app.test",
        "size" : 211,
        "count" : 5,
        "avgObjSize" : 42,
        "storageSize" : 36864,
        "freeStorageSize" : 16384,
        "capped" : false,
        "wiredTiger" : {
                "metadata" : {
                        "formatVersion" : 1
                },
                "creationString" : "access_pattern_hint=none,allocation_size=4KB,app_metadata=(formatVersion=1),assert=(commit_timestamp=none,durable_timestamp=none,read_timestamp=none,write_timestamp=off),block_allocation=best,block_compressor=snappy,cache_resident=false,checksum=on,colgroups=,collator=,columns=,dictionary=0,encryption=(keyid=,name=),exclusive=false,extractor=,format=btree,huffman_key=,huffman_value=,ignore_in_memory_cache_size=false,immutable=false,import=(enabled=false,file_metadata=,repair=false),internal_item_max=0,internal_key_max=0,internal_key_truncate=true,internal_page_max=4KB,key_format=q,key_gap=10,leaf_item_max=0,leaf_key_max=0,leaf_page_max=32KB,leaf_value_max=64MB,log=(enabled=true),lsm=(auto_throttle=true,bloom=true,bloom_bit_count=16,bloom_config=,bloom_hash_count=8,bloom_oldest=false,chunk_count_limit=0,chunk_max=5GB,chunk_size=10MB,merge_custom=(prefix=,start_generation=0,suffix=),merge_max=15,merge_min=0),memory_page_image_max=0,memory_page_max=10m,os_cache_dirty_max=0,os_cache_max=0,prefix_compression=false,prefix_compression_min=4,readonly=false,source=,split_deepen_min_child=0,split_deepen_per_child=0,split_pct=90,tiered_object=false,tiered_storage=(auth_token=,bucket=,bucket_prefix=,local_retention=300,name=,object_target_size=10M),type=file,value_format=u,verbose=[],write_timestamp_usage=none",
                "type" : "file",
                "uri" : "statistics:table:collection-10--2105812055033304131",
                "LSM" : {
                        "bloom filter false positives" : 0,
                        "bloom filter hits" : 0,
                        "bloom filter misses" : 0,
                        "bloom filter pages evicted from cache" : 0,
                        "bloom filter pages read into cache" : 0,
                        "bloom filters in the LSM tree" : 0,
                        "chunks in the LSM tree" : 0,
                        "highest merge generation in the LSM tree" : 0,
                        "queries that could have benefited from a Bloom filter that did not exist" : 0,
                        "sleep for LSM checkpoint throttle" : 0,
                        "sleep for LSM merge throttle" : 0,
                        "total size of bloom filters" : 0
                },
                "block-manager" : {
                        "allocations requiring file extension" : 10,
                        "blocks allocated" : 16,
                        "blocks freed" : 3,
                        "checkpoint size" : 4096,
                        "file allocation unit size" : 4096,
                        "file bytes available for reuse" : 16384,
                        "file magic number" : 120897,
                        "file major version number" : 1,
                        "file size in bytes" : 36864,
                        "minor version number" : 0
                },
                "btree" : {
                        "btree checkpoint generation" : 1090,
                        "btree clean tree checkpoint expiration time" : NumberLong("9223372036854775807"),
                        "column-store fixed-size leaf pages" : 0,
                        "column-store internal pages" : 0,
                        "column-store variable-size RLE encoded values" : 0,
                        "column-store variable-size deleted values" : 0,
                        "column-store variable-size leaf pages" : 0,
                        "fixed-record size" : 0,
                        "maximum internal page key size" : 368,
                        "maximum internal page size" : 4096,
                        "maximum leaf page key size" : 2867,
                        "maximum leaf page size" : 32768,
                        "maximum leaf page value size" : 67108864,
                        "maximum tree depth" : 3,
                        "number of key/value pairs" : 0,
                        "overflow pages" : 0,
                        "pages rewritten by compaction" : 0,
                        "row-store empty values" : 0,
                        "row-store internal pages" : 0,
                        "row-store leaf pages" : 0
                },
                "cache" : {
                        "bytes currently in the cache" : 1699,
                        "bytes dirty in the cache cumulative" : 5311,
                        "bytes read into cache" : 0,
                        "bytes written from cache" : 902,
                        "checkpoint blocked page eviction" : 0,
                        "checkpoint of history store file blocked non-history store page eviction" : 0,
                        "data source pages selected for eviction unable to be evicted" : 0,
                        "eviction walk passes of a file" : 0,
                        "eviction walk target pages histogram - 0-9" : 0,
                        "eviction walk target pages histogram - 10-31" : 0,
                        "eviction walk target pages histogram - 128 and higher" : 0,
                        "eviction walk target pages histogram - 32-63" : 0,
                        "eviction walk target pages histogram - 64-128" : 0,
                        "eviction walk target pages reduced due to history store cache pressure" : 0,
                        "eviction walks abandoned" : 0,
                        "eviction walks gave up because they restarted their walk twice" : 0,
                        "eviction walks gave up because they saw too many pages and found no candidates" : 0,
                        "eviction walks gave up because they saw too many pages and found too few candidates" : 0,
                        "eviction walks reached end of tree" : 0,
                        "eviction walks restarted" : 0,
                        "eviction walks started from root of tree" : 0,
                        "eviction walks started from saved location in tree" : 0,
                        "hazard pointer blocked page eviction" : 0,
                        "history store table insert calls" : 0,
                        "history store table insert calls that returned restart" : 0,
                        "history store table out-of-order resolved updates that lose their durable timestamp" : 0,
                        "history store table out-of-order updates that were fixed up by reinserting with the fixed timestamp" : 0,
                        "history store table reads" : 0,
                        "history store table reads missed" : 0,
                        "history store table reads requiring squashed modifies" : 0,
                        "history store table truncation by rollback to stable to remove an unstable update" : 0,
                        "history store table truncation by rollback to stable to remove an update" : 0,
                        "history store table truncation to remove an update" : 0,
                        "history store table truncation to remove range of updates due to key being removed from the data page during reconciliation" : 0,
                        "history store table truncation to remove range of updates due to out-of-order timestamp update on data page" : 0,
                        "history store table writes requiring squashed modifies" : 0,
                        "in-memory page passed criteria to be split" : 0,
                        "in-memory page splits" : 0,
                        "internal pages evicted" : 0,
                        "internal pages split during eviction" : 0,
                        "leaf pages split during eviction" : 0,
                        "modified pages evicted" : 0,
                        "overflow pages read into cache" : 0,
                        "page split during eviction deepened the tree" : 0,
                        "page written requiring history store records" : 0,
                        "pages read into cache" : 0,
                        "pages read into cache after truncate" : 1,
                        "pages read into cache after truncate in prepare state" : 0,
                        "pages requested from the cache" : 21,
                        "pages seen by eviction walk" : 0,
                        "pages written from cache" : 8,
                        "pages written requiring in-memory restoration" : 0,
                        "tracked dirty bytes in the cache" : 0,
                        "unmodified pages evicted" : 0
                },
                "cache_walk" : {
                        "Average difference between current eviction generation when the page was last considered" : 0,
                        "Average on-disk page image size seen" : 0,
                        "Average time in cache for pages that have been visited by the eviction server" : 0,
                        "Average time in cache for pages that have not been visited by the eviction server" : 0,
                        "Clean pages currently in cache" : 0,
                        "Current eviction generation" : 0,
                        "Dirty pages currently in cache" : 0,
                        "Entries in the root page" : 0,
                        "Internal pages currently in cache" : 0,
                        "Leaf pages currently in cache" : 0,
                        "Maximum difference between current eviction generation when the page was last considered" : 0,
                        "Maximum page size seen" : 0,
                        "Minimum on-disk page image size seen" : 0,
                        "Number of pages never visited by eviction server" : 0,
                        "On-disk page image sizes smaller than a single allocation unit" : 0,
                        "Pages created in memory and never written" : 0,
                        "Pages currently queued for eviction" : 0,
                        "Pages that could not be queued for eviction" : 0,
                        "Refs skipped during cache traversal" : 0,
                        "Size of the root page" : 0,
                        "Total number of pages currently in cache" : 0
                },
                "checkpoint-cleanup" : {
                        "pages added for eviction" : 0,
                        "pages removed" : 0,
                        "pages skipped during tree walk" : 0,
                        "pages visited" : 4
                },
                "compression" : {
                        "compressed page maximum internal page size prior to compression" : 4096,
                        "compressed page maximum leaf page size prior to compression " : 131072,
                        "compressed pages read" : 0,
                        "compressed pages written" : 0,
                        "page written failed to compress" : 0,
                        "page written was too small to compress" : 8
                },
                "cursor" : {
                        "Total number of entries skipped by cursor next calls" : 0,
                        "Total number of entries skipped by cursor prev calls" : 0,
                        "Total number of entries skipped to position the history store cursor" : 0,
                        "Total number of pages skipped without reading by cursor next calls" : 0,
                        "Total number of pages skipped without reading by cursor prev calls" : 0,
                        "Total number of times a search near has exited due to prefix config" : 0,
                        "bulk loaded cursor insert calls" : 0,
                        "cache cursors reuse count" : 15,
                        "close calls that result in cache" : 18,
                        "create calls" : 3,
                        "cursor next calls that skip due to a globally visible history store tombstone" : 0,
                        "cursor next calls that skip greater than or equal to 100 entries" : 0,
                        "cursor next calls that skip less than 100 entries" : 43,
                        "cursor prev calls that skip due to a globally visible history store tombstone" : 0,
                        "cursor prev calls that skip greater than or equal to 100 entries" : 0,
                        "cursor prev calls that skip less than 100 entries" : 1,
                        "insert calls" : 5,
                        "insert key and value bytes" : 216,
                        "modify" : 0,
                        "modify key and value bytes affected" : 0,
                        "modify value bytes modified" : 0,
                        "next calls" : 43,
                        "open cursor count" : 0,
                        "operation restarted" : 0,
                        "prev calls" : 1,
                        "remove calls" : 0,
                        "remove key bytes removed" : 0,
                        "reserve calls" : 0,
                        "reset calls" : 37,
                        "search calls" : 0,
                        "search history store calls" : 0,
                        "search near calls" : 0,
                        "truncate calls" : 0,
                        "update calls" : 0,
                        "update key and value bytes" : 0,
                        "update value size change" : 0
                },
                "reconciliation" : {
                        "approximate byte size of timestamps in pages written" : 0,
                        "approximate byte size of transaction IDs in pages written" : 0,
                        "dictionary matches" : 0,
                        "fast-path pages deleted" : 0,
                        "internal page key bytes discarded using suffix compression" : 0,
                        "internal page multi-block writes" : 0,
                        "internal-page overflow keys" : 0,
                        "leaf page key bytes discarded using prefix compression" : 0,
                        "leaf page multi-block writes" : 0,
                        "leaf-page overflow keys" : 0,
                        "maximum blocks required for a page" : 1,
                        "overflow values written" : 0,
                        "page checksum matches" : 0,
                        "page reconciliation calls" : 8,
                        "page reconciliation calls for eviction" : 0,
                        "pages deleted" : 0,
                        "pages written including an aggregated newest start durable timestamp " : 0,
                        "pages written including an aggregated newest stop durable timestamp " : 0,
                        "pages written including an aggregated newest stop timestamp " : 0,
                        "pages written including an aggregated newest stop transaction ID" : 0,
                        "pages written including an aggregated newest transaction ID " : 0,
                        "pages written including an aggregated oldest start timestamp " : 0,
                        "pages written including an aggregated prepare" : 0,
                        "pages written including at least one prepare" : 0,
                        "pages written including at least one start durable timestamp" : 0,
                        "pages written including at least one start timestamp" : 0,
                        "pages written including at least one start transaction ID" : 0,
                        "pages written including at least one stop durable timestamp" : 0,
                        "pages written including at least one stop timestamp" : 0,
                        "pages written including at least one stop transaction ID" : 0,
                        "records written including a prepare" : 0,
                        "records written including a start durable timestamp" : 0,
                        "records written including a start timestamp" : 0,
                        "records written including a start transaction ID" : 0,
                        "records written including a stop durable timestamp" : 0,
                        "records written including a stop timestamp" : 0,
                        "records written including a stop transaction ID" : 0
                },
                "session" : {
                        "object compaction" : 0,
                        "tiered operations dequeued and processed" : 0,
                        "tiered operations scheduled" : 0,
                        "tiered storage local retention time (secs)" : 0,
                        "tiered storage object size" : 0
                },
                "transaction" : {
                        "race to read prepared update retry" : 0,
                        "rollback to stable history store records with stop timestamps older than newer records" : 0,
                        "rollback to stable inconsistent checkpoint" : 0,
                        "rollback to stable keys removed" : 0,
                        "rollback to stable keys restored" : 0,
                        "rollback to stable restored tombstones from history store" : 0,
                        "rollback to stable restored updates from history store" : 0,
                        "rollback to stable sweeping history store keys" : 0,
                        "rollback to stable updates removed from history store" : 0,
                        "transaction checkpoints due to obsolete pages" : 0,
                        "update conflicts" : 0
                }
        },
        "nindexes" : 1,
        "indexBuilds" : [ ],
        "totalIndexSize" : 36864,
        "totalSize" : 73728,
        "indexSizes" : {
                "_id_" : 36864
        },
        "scaleFactor" : 1,
        "ok" : 1
}

3、删除集合

db.test2.drop()

4、新增单一文档

db.test.insert({"name":"sunyuhua","age":26,"title":"cto"})
WriteResult({ "nInserted" : 1 })
> db.test.insert({"name":"sunyuhua","age":26,"title":"cto"})
WriteResult({ "nInserted" : 1 })
> db.test.find()
{ "_id" : ObjectId("613c7060f832314229fba0dd"), "name" : "sunyhua" }
{ "_id" : ObjectId("613d669e21ebb2c51ece4697"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66cd21ebb2c51ece4698"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66df21ebb2c51ece4699"), "name" : "sunyuhua111" }
{ "_id" : ObjectId("613d6e82dbe8e0b55ca50709"), "name" : "zhangsanfeng" }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070a"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070b"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070c"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
{ "_id" : ObjectId("613d70efdbe8e0b55ca5070d"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
{ "_id" : ObjectId("613d710edbe8e0b55ca5070e"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
>

5、批量新增文档

 db.test.insert([{title:'java',tags:['JavaSE','JavaEE','JavaME']},{title:'ORM',tags:['Mybatis','Hibernate']},{title:'Spring',tags:['SpringMVC','SpringBoot','SpringCloud']}])
> db.test.insert([{title:'java',tags:['JavaSE','JavaEE','JavaME']},{title:'ORM',tags:['Mybatis','Hibernate']},{title:'Spring',tags:['SpringMVC','SpringBoot','SpringCloud']}])
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 3,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})
> db.test.find()
{ "_id" : ObjectId("613c7060f832314229fba0dd"), "name" : "sunyhua" }
{ "_id" : ObjectId("613d669e21ebb2c51ece4697"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66cd21ebb2c51ece4698"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66df21ebb2c51ece4699"), "name" : "sunyuhua111" }
{ "_id" : ObjectId("613d6e82dbe8e0b55ca50709"), "name" : "zhangsanfeng" }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070a"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070b"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070c"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }

mangoDB3.2 以后的版本推荐使用 insertMany函数

db.test.insertMany([{title:'java',tags:['JavaSE','JavaEE','JavaME']},{title:'ORM',tags:['Mybatis','Hibernate']},{title:'Spring',tags:['SpringMVC','SpringBoot','SpringCloud']}])
> db.test.insertMany([{title:'java',tags:['JavaSE','JavaEE','JavaME']},{title:'ORM',tags:['Mybatis','Hibernate']},{title:'Spring',tags:['SpringMVC','SpringBoot','SpringCloud']}])
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("613d7174dbe8e0b55ca5070f"),
                ObjectId("613d7174dbe8e0b55ca50710"),
                ObjectId("613d7174dbe8e0b55ca50711")
        ]
}
> db.test.insertMany([{title:'java',tags:['JavaSE','JavaEE','JavaME']},{title:'ORM',tags:['Mybatis','Hibernate']},{title:'Spring',tags:['SpringMVC','SpringBoot','SpringCloud']}])
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("613d7214dbe8e0b55ca50712"),
                ObjectId("613d7214dbe8e0b55ca50713"),
                ObjectId("613d7214dbe8e0b55ca50714")
        ]
}
> db.test.find()
{ "_id" : ObjectId("613c7060f832314229fba0dd"), "name" : "sunyhua" }
{ "_id" : ObjectId("613d669e21ebb2c51ece4697"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66cd21ebb2c51ece4698"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66df21ebb2c51ece4699"), "name" : "sunyuhua111" }
{ "_id" : ObjectId("613d6e82dbe8e0b55ca50709"), "name" : "zhangsanfeng" }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070a"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070b"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070c"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
{ "_id" : ObjectId("613d70efdbe8e0b55ca5070d"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
{ "_id" : ObjectId("613d710edbe8e0b55ca5070e"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
{ "_id" : ObjectId("613d7174dbe8e0b55ca5070f"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca50710"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca50711"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50712"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50713"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50714"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
>

6、查询文档

findOne()函数用于查询集合中的一个文档

db.test.find({name:"sunyuhua"})
> db.test.find({name:"sunyuhua"})
{ "_id" : ObjectId("613d669e21ebb2c51ece4697"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66cd21ebb2c51ece4698"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d70efdbe8e0b55ca5070d"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
{ "_id" : ObjectId("613d710edbe8e0b55ca5070e"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
> db.test.findOne({name:"sunyuhua"})
{ "_id" : ObjectId("613d669e21ebb2c51ece4697"), "name" : "sunyuhua" }
>

查询第一个名字,并且显示指定的字段

db.test.find({"title":"java"},{"title":1})
> db.test.find()
{ "_id" : ObjectId("613c7060f832314229fba0dd"), "name" : "sunyhua" }
{ "_id" : ObjectId("613d669e21ebb2c51ece4697"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66cd21ebb2c51ece4698"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66df21ebb2c51ece4699"), "name" : "sunyuhua111" }
{ "_id" : ObjectId("613d6e82dbe8e0b55ca50709"), "name" : "zhangsanfeng" }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070a"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070b"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070c"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
{ "_id" : ObjectId("613d70efdbe8e0b55ca5070d"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
{ "_id" : ObjectId("613d710edbe8e0b55ca5070e"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
{ "_id" : ObjectId("613d7174dbe8e0b55ca5070f"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca50710"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca50711"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50712"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50713"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50714"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
> db.test.find({"title":"java"},{"title":1})
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070a"), "title" : "java" }
{ "_id" : ObjectId("613d7174dbe8e0b55ca5070f"), "title" : "java" }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50712"), "title" : "java" }

7、多条件逻辑查找

1、and条件查询

> db.test.find()
{ "_id" : ObjectId("613c7060f832314229fba0dd"), "name" : "sunyhua" }
{ "_id" : ObjectId("613d669e21ebb2c51ece4697"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66cd21ebb2c51ece4698"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66df21ebb2c51ece4699"), "name" : "sunyuhua111" }
{ "_id" : ObjectId("613d6e82dbe8e0b55ca50709"), "name" : "zhangsanfeng" }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070a"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070b"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070c"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
{ "_id" : ObjectId("613d70efdbe8e0b55ca5070d"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
{ "_id" : ObjectId("613d710edbe8e0b55ca5070e"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
{ "_id" : ObjectId("613d7174dbe8e0b55ca5070f"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca50710"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca50711"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50712"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50713"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50714"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
> db.test.find({"name":"sunyuhua","age":26})
{ "_id" : ObjectId("613d70efdbe8e0b55ca5070d"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
{ "_id" : ObjectId("613d710edbe8e0b55ca5070e"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }

2、or的查询条件

db.test.find({$or:[{"name":"sunyuhua111"},{"name":"sunyuhua"}]})
> db.test.find({$or:[{"name":"sunyuhua111"},{"name":"sunyuhua"}]})
{ "_id" : ObjectId("613d669e21ebb2c51ece4697"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66cd21ebb2c51ece4698"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66df21ebb2c51ece4699"), "name" : "sunyuhua111" }
{ "_id" : ObjectId("613d70efdbe8e0b55ca5070d"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
{ "_id" : ObjectId("613d710edbe8e0b55ca5070e"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }

3、 $type查询

db.test.find({"tags":{$type:"array"}})
> db.test.find()
{ "_id" : ObjectId("613c7060f832314229fba0dd"), "name" : "sunyhua" }
{ "_id" : ObjectId("613d669e21ebb2c51ece4697"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66cd21ebb2c51ece4698"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66df21ebb2c51ece4699"), "name" : "sunyuhua111" }
{ "_id" : ObjectId("613d6e82dbe8e0b55ca50709"), "name" : "zhangsanfeng" }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070a"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070b"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070c"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
{ "_id" : ObjectId("613d70efdbe8e0b55ca5070d"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
{ "_id" : ObjectId("613d710edbe8e0b55ca5070e"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
{ "_id" : ObjectId("613d7174dbe8e0b55ca5070f"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca50710"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca50711"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50712"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50713"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50714"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
> db.test.find({"tags":{$type:"array"}})
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070a"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070b"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070c"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca5070f"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca50710"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca50711"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50712"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50713"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50714"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }

4、正则表达式查询

> db.test.find({"name":/^sun/})
{ "_id" : ObjectId("613c7060f832314229fba0dd"), "name" : "sunyhua" }
{ "_id" : ObjectId("613d669e21ebb2c51ece4697"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66cd21ebb2c51ece4698"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66df21ebb2c51ece4699"), "name" : "sunyuhua111" }
{ "_id" : ObjectId("613d70efdbe8e0b55ca5070d"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
{ "_id" : ObjectId("613d710edbe8e0b55ca5070e"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
> db.test.find({"name":/hua$/})
{ "_id" : ObjectId("613c7060f832314229fba0dd"), "name" : "sunyhua" }
{ "_id" : ObjectId("613d669e21ebb2c51ece4697"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66cd21ebb2c51ece4698"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d70efdbe8e0b55ca5070d"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
{ "_id" : ObjectId("613d710edbe8e0b55ca5070e"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
> db.test.find({"name":/a/})
{ "_id" : ObjectId("613c7060f832314229fba0dd"), "name" : "sunyhua" }
{ "_id" : ObjectId("613d669e21ebb2c51ece4697"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66cd21ebb2c51ece4698"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66df21ebb2c51ece4699"), "name" : "sunyuhua111" }
{ "_id" : ObjectId("613d6e82dbe8e0b55ca50709"), "name" : "zhangsanfeng" }
{ "_id" : ObjectId("613d70efdbe8e0b55ca5070d"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
{ "_id" : ObjectId("613d710edbe8e0b55ca5070e"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
> db.test.find({"name":/^s.*a$/})
{ "_id" : ObjectId("613c7060f832314229fba0dd"), "name" : "sunyhua" }
{ "_id" : ObjectId("613d669e21ebb2c51ece4697"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66cd21ebb2c51ece4698"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d70efdbe8e0b55ca5070d"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
{ "_id" : ObjectId("613d710edbe8e0b55ca5070e"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
> db.test.find({"name":{$not:/^s/}})
{ "_id" : ObjectId("613d6e82dbe8e0b55ca50709"), "name" : "zhangsanfeng" }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070a"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070b"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070c"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca5070f"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca50710"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca50711"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50712"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50713"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50714"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
> db.test.find({"name":{$nin:[/^s/]}})
{ "_id" : ObjectId("613d6e82dbe8e0b55ca50709"), "name" : "zhangsanfeng" }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070a"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070b"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070c"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca5070f"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca50710"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca50711"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50712"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50713"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50714"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
>

5、分页查询

> db.test.find().limit(2)
{ "_id" : ObjectId("613c7060f832314229fba0dd"), "name" : "sunyhua" }
{ "_id" : ObjectId("613d669e21ebb2c51ece4697"), "name" : "sunyuhua" }

6、跳过函数

> db.test.find().limit(2)
{ "_id" : ObjectId("613c7060f832314229fba0dd"), "name" : "sunyhua" }
{ "_id" : ObjectId("613d669e21ebb2c51ece4697"), "name" : "sunyuhua" }
> db.test.find().limit(2).skip(1)
{ "_id" : ObjectId("613d669e21ebb2c51ece4697"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66cd21ebb2c51ece4698"), "name" : "sunyuhua" }
>

7、排序函数

> db.test.find().limit().sort({"name":1})
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070a"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070b"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070c"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca5070f"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca50710"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca50711"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50712"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50713"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50714"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
{ "_id" : ObjectId("613c7060f832314229fba0dd"), "name" : "sunyhua" }
{ "_id" : ObjectId("613d669e21ebb2c51ece4697"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66cd21ebb2c51ece4698"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d70efdbe8e0b55ca5070d"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
{ "_id" : ObjectId("613d710edbe8e0b55ca5070e"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
{ "_id" : ObjectId("613d66df21ebb2c51ece4699"), "name" : "sunyuhua111" }
{ "_id" : ObjectId("613d6e82dbe8e0b55ca50709"), "name" : "zhangsanfeng" }
> db.test.find().limit().sort({"name":-1})
{ "_id" : ObjectId("613d6e82dbe8e0b55ca50709"), "name" : "zhangsanfeng" }
{ "_id" : ObjectId("613d66df21ebb2c51ece4699"), "name" : "sunyuhua111" }
{ "_id" : ObjectId("613d669e21ebb2c51ece4697"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d66cd21ebb2c51ece4698"), "name" : "sunyuhua" }
{ "_id" : ObjectId("613d70efdbe8e0b55ca5070d"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
{ "_id" : ObjectId("613d710edbe8e0b55ca5070e"), "name" : "sunyuhua", "age" : 26, "title" : "cto" }
{ "_id" : ObjectId("613c7060f832314229fba0dd"), "name" : "sunyhua" }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070a"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070b"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d6fc6dbe8e0b55ca5070c"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca5070f"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca50710"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d7174dbe8e0b55ca50711"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50712"), "title" : "java", "tags" : [ "JavaSE", "JavaEE", "JavaME" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50713"), "title" : "ORM", "tags" : [ "Mybatis", "Hibernate" ] }
{ "_id" : ObjectId("613d7214dbe8e0b55ca50714"), "title" : "Spring", "tags" : [ "SpringMVC", "SpringBoot", "SpringCloud" ] }

8、更新文档

db.test.save(
    {
        "_id" : ObjectId("5d0207e460ad10791be757d2"),
        "title" : "MongoDB 教程",
        "description" : "MongoDB 是一个 Nosql 数据库",
        "by" : "北京尚学堂",
        "tags" : [
            "mongodb",
            "NoSQL"
        ],
        "likes" : 100
    }
)

9、更新文档

MongoDB通过update函数与save函数来更新集合中的文档。

1、save更新文档

save()函数的作用是保存文档,如果文档存在则覆盖,如果文档不存在则新增。save()函数对文档是否存在的唯一判断标准是"_id"系统唯一字段是否匹配。所以使用save()函数实现更新操作,则必须提供"_id"字段数据。
save()函数的语法是:

db.集合名称.save(
    <document>
);

参数document代表要修改的文档内容,要求必须提供"_id"字段数据。

使用save()函数实现更新操作:

db.test.save(
    {
        "_id" : ObjectId("5d0207e460ad10791be757d2"),
        "title" : "MongoDB 教程",
        "description" : "MongoDB 是一个 Nosql 数据库",
        "by" : "北京尚学堂",
        "tags" : [
            "mongodb",
            "NoSQL"
        ],
        "likes" : 100
    }
)

2、update更新文档

update() 函数用于更新已存在的文档。
语法格式:

db.集合名称.update(
    <query>,
    <update>,
    < upsert:boolean>,
    < multi:boolean>
)

参数说明:
query : update的查询条件,类似sql update更新语法内where后面的内容。
update : update的对象和一些更新的操作符等,也可以理解为sql update查询内set后面的。
upsert : 可选,这个参数的意思是,如果不存在update的记录,是否插入这个document,true为插入,默认是false,不插入。只有在表达式更新语法中才可使用。
multi : 可选,mongodb 默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。只有在表达式更新语法中才可使用。
在MongoDB中的update是有两种更新方式,一种是覆盖更新,一种是表达式更新。
覆盖更新:顾名思义,就是通过某条件,将新文档覆盖原有文档。
表达式更新:这种更新方式是通过表达式来实现复杂更新操作,如:字段更新、数值计算、数组操作、字段名修改等。

2.1覆盖更新

通过update方法来更新一个完整的文档:

db.col.update(
    {"title" : "MongoDB 教程"},
    {
        "title" : "MongoDB 教程",
        "description" : "MongoDB 是一个 Nosql 数据库",
        "by" : "北京尚学堂",
        "likes" : 100
    }
)
2.2表达式更新

语法:

db.集合名称.update(
    <query>,
    <doc_projection>,
    <upsert>,
    <multi>
);

doc_projection语法:
{
$表达式:{具体更新规则}
}

1$inc

用法:{$inc:{field:value}}

作用:对一个数字字段的某个field增加value

示例:将name为zhangsan的学生的age增加5

命令:db.stu.update({name:"zhangsan"},{$inc:{age:5}})

2$set

用法:{$set:{field:value}}

作用:把文档中某个字段field的值设为value,如果field不存在,则增加新的字段并赋值为value。

示例:把zhangsan的年龄设为23岁

命令:db.stu.update({name:"zhangsan"},{$set:{'age':23}})

3$unset

用法:{$unset:{field:1}}

作用:删除某个字段field

示例:将zhangsan的年龄字段删除

命令:db.stu.update({name:"zhangsan"},{$unset:{age:1}})

4$push

用法:{$push:{field:value}}

作用:把value追加到field里。注:field只能是数组类型,如果field不存在,会自动插入一个数组类型

示例:给zhangsan添加别名"xiaozhang"

命令:db.stu.update({name:"zhangsan"},{$push:{"alias":"xiaozhang"}})

5$addToSet

用法:{$addToSet:{field:value}}

作用:加一个值到数组内,而且只有当这个值在数组中不存在时才增加。
示例:往zhangsan的别名字段里添加两个别名A1、A2

命令:db.stu.update({name:“zhangsan”},{$addToSet:{“alias”:[“A1”,“A2”]}})

注意:此处加入的数据是一个数据为A1和A2的数组对象。并不是将两个数据依次加入alias数组中。

6$pop

用法:删除数组内第一个值:{KaTeX parse error: Expected 'EOF', got '}' at position 15: pop:{field:-1}}̲、删除数组内最后一个值:{pop:{field:1}}

作用:用于删除数组内的一个值

示例:删除zhangsan记录中alias字段中最后一个别名

命令:db.stu.update({name:"zhangsan"},{$pop:{"alias":1}})

7$pull

用法:{$pull:{field:_value}}

作用:从数组field内删除所有等于_value的值

示例:删除zhangsan记录中的别名xiaozhang

命令:db.stu.update({name:"zhangsan"},{$pull:{"alias":"xiaozhang"}})

8$pullAll

用法:{$pullAll:value_array}

作用:用法同$pull一样,可以一次性删除数组内的多个值。

示例:删除zhangsan记录内的A1和A2别名

命令:db.stu.update({name:"zhangsan"},{$pullAll:{"alias":["A1","A2"]}})

9$rename

用法:{$rename:{old_field_name:new_field_name}}

作用:对字段进行重命名。底层实现是先删除old_field字段,再创建new_field字段。

示例:把zhangsan记录的name字段重命名为sname

命令:db.stu.update({name:"zhangsan"},{$rename:{"name":"sname"}})

10更多案例

只更新第一条满足条件的记录:

db.col.update( { "count" : { $gt : 1 } } , { $set : { "test2" : "OK"} } );

更新全部满足条件的记录:

db.col.update( { "count" : { $gt : 3 } } , { $set : { "test2" : "OK"} },false,true );

如果没有符合条件的数据,则添加一条:

db.col.update( { "count" : { $gt : 4 } } , { $set : { "test5" : "OK"} },true,false );

如果没有符合条件的数据,则全部添加进去:

db.col.update( { "count" : { $gt : 5 } } , { $set : { "test5" : "OK"} },true,true );

只更新第一条记录:(等同第一个)

db.col.update( { "count" : { $lt : 10 } } , { $set : { "count" : 1} },false,false );

4删除文档

MongoDB是通过remove()函数、deleteOne()函数、deleteMany()函数来删除集合中的文档。
4.1remove函数
语法格式是:

db.集合名称.remove(
    <query>,
    <justOne:boolean>
);

参数说明:
query:要删除的文档条件,相当于SQL语法中的where子句作用。
justOne:可选参数,布尔类型,代表是否只删除第一个匹配条件满足的文档。默认值为false,代表删除全部满足匹配条件的文档。
注意:此方法已经过时,官方推荐使用deleteOne()和deleteMany()函数来实现删除操作。且在4.0-版本中,remove()函数并不会真正的释放存储空间,需要使用db.repairDatabase()函数来释放存储空间。在4.2.1版本中,删除函数repairDatabase()。

1删除全部

删除stus集合中的全部文档:
db.stus.remove({});

2条件删除

删除stus集合中age字段为10的文档。

db.stus.remove({'age':10});

删除stus集合中age字段大于20的第一个文档。

db.stus.remove({'age':{'$gt':20}}, true);

删除stus集合中age字段小于50的全部文档。

db.stus.remove({'age':{'$lt':50}});

db.stus.remove({'age':{'$lt':50}}, false);
2deleteOne函数

语法格式:

db.集合名称.deleteOne({<query>});

参数解释:
query:要删除的文档条件,相当于SQL语法中的where子句作用。

删除stus集合中name字段为zhangsan的第一个文档:
db.stus.deleteOne({‘name’:‘zhangsan’});

3deleteMany函数

语法格式:
db.集合名称.deleteMany({});
参数解释:
query:要删除的文档条件,相当于SQL语法中的where子句作用。

删除stus集合中age字段大于10的所有文档:
db.stus.deleteMany({‘age’:{’$gt’:10}});

内置函数

MongoDB中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果。聚合框架是MongoDB的高级查询语言,允许我们通过转化合并由多个文档的数据来生成新的在单个文档里不存在的文档信息。通俗一点来说,可以把MongoDB的聚合查询等价于SQL的GROUP BY语句。
测试数据

db.coll.insertMany([
{"name":"zhangsan", "age":20, "gender":"male", "birth":new ISODate('2000-01-01')},
{"name":"lisi", "age":21, "gender":"male", "birth":new ISODate('1999-02-01')},
{"name":"wangwu", "age":20, "gender":"female", "birth":new ISODate('2000-01-01')},
{"name":"zhaoliu", "age":22, "gender":"female", "birth":new ISODate('1998-01-01')}]);

1aggregate函数

MongoDB中聚合的方法使用aggregate()。
语法:

db.集合名称.aggregate(<agg_options>)

参数解释:
agg_options:数组类型参数,传入具体的聚合表达式要求,来计算聚合结果。此参数代表聚合规则,如计算总和、平均值、最大最小值等。在MongoDB的聚合查询中,操作复杂度都在这里。

求和 $sum

统计coll集合中所有文档age字段的总和:

db.coll.aggregate([{"$group":{"_id":null, "sum_age":{"$sum":"$age"}}}])	

语法解释:
g r o u p : 分 组 , 代 表 聚 合 的 分 组 条 件 i d : 分 组 的 字 段 。 相 当 于 S Q L 分 组 语 法 g r o u p b y c o l u m n n a m e 中 的 c o l u m n n a m e 部 分 。 如 果 根 据 某 字 段 的 值 分 组 , 则 定 义 为 i d : ′ group:分组,代表聚合的分组条件 _id:分组的字段。相当于SQL分组语法group by column_name中的column_name部分。如果根据某字段的值分组,则定义为_id:' groupidSQLgroupbycolumnnamecolumnnameid:字段名’。所以此案例中的null代表一个固定的字面值’null’。
sum_age:返回结果字段名。可以自定义,类似SQL中的字段别名。
$sum:求和表达式。相当于SQL中的sum()。
a g e : 代 表 文 档 中 的 a g e 字 段 的 值 。 此 案 例 中 的 age:代表文档中的age字段的值。此案例中的 ageagesum:' a g e ′ 代 表 求 文 档 中 a g e 字 段 的 和 。 如 果 案 例 定 义 为 age'代表求文档中age字段的和。如果案例定义为 ageagesum:‘age’,代表求age字面值的和。在MongoDB中,字符串是不会进行数学相关运算的。得到的求和结果一定是0。

统计文档数量

聚合统计coll集合中文档数量:

db.coll.aggregate([{$group:{_id:null, count:{$sum:1}}}]);

统计coll集合中,相同年龄的文档数量:

db.coll.aggregate([{"$group":{"_id":"$age", "count":{"$sum":1}}}])

语法解释:
_id:'KaTeX parse error: Expected '}', got 'EOF' at end of input: …进行分组。 doc_num:{sum:1} : 求和计算。每个符合条件的文档计数为1,进行累加求和。返回的结果作为字段doc_num的值。

条件筛选

统计coll集合中,年龄小于22的文档数量:

db.coll.aggregate([{"$match":{"age":{"$lt":22}}}, {"$group":{"_id":null, "count":{"$sum":1}}}])

语法解释:
KaTeX parse error: Expected '}', got 'EOF' at end of input: …行条件筛选。 {'age':{lt:21}}:age字段小于21。

统计agg集合中,相同年龄的文档数量,且要求统计结果中,同年龄的文档数量大于1:

db.coll.aggregate([{"$group":{"_id":"$age", "count":{"$sum":1}}}, {"$match":{"count":{"$gt":1}}}])

语法解释:
{KaTeX parse error: Expected '}', got 'EOF' at end of input: group:{_id:'age’, “count”:{KaTeX parse error: Expected 'EOF', got '}' at position 6: sum:1}̲}}:统计每个age字段值的文…match:{“count”:{$gt:1}}}:匹配条件,相当于SQL中的having子句。代表聚合之后进行条件筛选,只能筛选聚合结果,不能筛选聚合条件。返回nums字段值大于1的结果。

注意: m a t c h 表 达 式 定 义 的 位 置 不 同 , 代 表 的 筛 选 时 机 不 同 , 根 据 具 体 情 况 , 合 理 的 定 义 match表达式定义的位置不同,代表的筛选时机不同,根据具体情况,合理的定义 matchmatch表达式,可以有效提升聚合查询效率。尽可能先筛选过滤更多的无效数据,再group分组,效率最好。

最大值 $max

查询coll集合中age字段最大的文档:

db.coll.aggregate([{"$group":{"_id":null, "max_age":{"$max":"$age"}}}])
最小值 $min

查询coll集合中birth字段最小的文档:

db.coll.aggregate([{"$group":{"_id":null, "min_age":{"$min":"$age"}}}])
平均值 $avg

查询coll集合中所有文档age字段的平均值:

db.coll.aggregate([{"$group":{"_id":null, "avg_age":{"$avg":"$age"}}}])
字符串拼接

c o n c a t ′ : [ ′ concat':[' concat:[字段名’, ‘固定字符串值’, ‘其他字符串类型字段或固定字段值’]
拼接coll集合中,name字段和gender字段。

db.coll.aggregate([{"$project":{"all_info":{"$concat":["$name"," - ","$gender"]}}}])

KaTeX parse error: Expected '}', got 'EOF' at end of input: … {"all_info":{"concat":[“ n a m e " , " − " , " name"," - "," name","","gender”]}} - all_info定义别名, 处理后的结果的别名
c o n c a t " : [ " concat":[" concat":["name”," - “,”$gender"] - c o n c a t − 字 符 串 拼 接 表 达 式 ( 函 数 ) , 对 应 的 参 数 值 是 一 个 数 组 , 数 组 中 的 每 个 元 素 就 是 要 拼 接 的 字 符 串 , " 字 面 值 " 或 " concat - 字符串拼接表达式(函数),对应的参数值是一个数组,数组中的每个元素就是要拼接的字符串,"字面值"或" concat"""字段名"。

字符串转大写

t o U p p e r ′ : ′ toUpper':' toUpper:字段名’

db.coll.aggregate([{"$project":{"upperName":{"$toUpper":"$name"}}}])
字符串转小写

t o L o w e r ′ : ′ toLower':' toLower:字段名’

db.coll.aggregate([{"$project":{"lowerGender":{"$toLower":"$gender"}}}])

姓名转大写,性别转小写:

db.coll.aggregate([{"$project":{"lowerGender":{"$toLower":"$gender"}, "upperName":{"$toUpper":"$name"}}}])
截取字符串

s u b s t r ′ : [ ′ substr':[' substr:[字段名’,起始下标,截取长度]

db.coll.aggregate([{"$project":{"subName":{"$substr":["$name", 0, 3]}}}])
日期格式化
db.agg.aggregate([{'$project':{'str':{'$dateToString':{'format':'%Y年%m月%d日 %H:%M:%S', 'date':'$birth'}}}}]);

{'KaTeX parse error: Expected '}', got 'EOF' at end of input: …H:%M:%S",date:"birth"}}:使用MongoDB中的日期占位表达式格式化birth字段的数据。%Y年、%m月、%d日、%H 24小时制、%M分钟、%S秒。具体表达式含义如下:

运算符

在MongoDB中,数学类型(int/long/double)和日期类型(date)可以做数学运行。日期只能做加减。日期加减单位是毫秒。因为MongoDB底层记录日期的方式是:1970-01-01 00:00:00.000到日期所在时间经历的毫秒数。

加法

查询agg集合中数据,显示name和age字段,并为age字段数据做加1操作:

db.agg.aggregate([{$project:{name:1, new_age:{$add:['$age', 1]}}}]);
减法

查询agg集合中数据,显示name和age字段,并为age字段数据做减1操作:

db.agg.aggregate([{$project:{name:1, new_age:{$subtract:['$age', 1]}}}]);
乘法

查询agg集合中数据,显示name和age字段,并为age字段数据做乘2操作:

db.agg.aggregate([{$project:{name:1, new_age:{$multiply:['$age', 2]}}}]);
除法

查询agg集合中数据,显示name和age字段,并为age字段数据做除2操作:

db.agg.aggregate([{$project:{name:1, new_age:{$divide:['$age', 2]}}}]);
取模

查询agg集合中数据,显示name和age字段,并为age字段数据做模2操作:

db.agg.aggregate([{$project:{name:1, new_age:{$mod:['$age', 2]}}}]);
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MonkeyKing.sun

对你有帮助的话,可以打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值