MongoDB Common Basic Commands

Posted by jackel15 on Sat, 08 Jun 2019 01:10:51 +0200

mongoDB database

The concept of mongoDB database

An instance of MongoDB can have one or more independent databases, each with its own collection.

aggregate

Collections can be seen as tables with dynamic schemas.

File

Documents are the basic data units in MongoDB, similar to rows of relational database tables.
Documents are an ordered set of key-value pairs.

_id

Each document has a special "_id", which is unique in the collection to which the document belongs.

When the mongo command links to the MongoDB database, it enters the javascript shell

MongoDB comes with a powerful JavaScript Shell that can be used to manage or operate MongoDB.

Database naming rules

* 1: It can't be an empty string.

* 2: Do not contain /,\?, $, spaces, blank characters, etc. Basically, only the letters and numbers in ASCII can be used.

* 3: Case-sensitive, suggesting all lowercase.

* 4: A maximum of 64 bytes.

* 5: Do not use reserved database names, such as admin,local,config 

Note: The database will eventually become a file. The name of the database is the name of the file.

Set Name Definition Rules

  • 1: It can't be an empty string.

  • 2: Cannot contain the0 character (empty character), which means the end of the collection name, nor can it contain "$".

  • 3: You can't start with "system." This is the prefix reserved for the system set.

key Definition Rules for Documents

* 1: Cannot contain the0 character (empty character), which represents the end of the key.
* 2: "." and "$" are reserved and can only be used in specific circumstances.
* 3: Type-sensitive, but also case-sensitive.
* 4: Keys cannot be repeated

Note: Document key value pairs are ordered, and the same key value pairs are different documents if they have different order.

Database operation

Display the existing database.

    show dbs

    leyue   0.078GB
    local   0.078GB
    mongo   0.078GB
    mycol   0.078GB
    mydb    0.078GB
    testdb  0.078GB

Display the data currently in use.

    db

Switch the database currently in use.

    use leyue

Create a database

    use database name
    db. Collection name. insert({"name":"wang wu"})

    Create a database: MongoDB does not have a statement specifically for creating a database. You can use "use" to use a database if you want to use it
 If the database does not exist, it will be created and saved as a file after the document is actually added to the database.

Delete the database

    use Database name
    db.dropDatabase()

Operations of collections

Create collections

    Create collections: You don't need to create collections in MongoDB, because there is no fixed structure, you can use db. Collection name. Command to operate directly.
That's it. If you have to show the created collection, use: db.createCollecion("Collection Name");

Display existing collections

    use leyue

    show collections

Insert can insert one {} multiple data for []

    db.userdatas.insert([ {"name":'lisan',"age":23},{"name":"wang wu","age":33} ])
1:MongoDB automatically adds a "_id" field to every document that does not have a "_id" field
 2: Each Doc must be less than 16MB

Delete document db. collection. remove()

    db.userdatas.remove({"name":"lisan"})

Viewing the status of database documents, you can see the number and size of documents, and so on.

    Database: db.stats()
    //Document: db. Collection.stats
    db.stats()
    {
        "db" : "leyue",
        "collections" : 4,
        "objects" : 418,
        "avgObjSize" : 110.77511961722487,
        "dataSize" : 46304,
        "storageSize" : 192512,
        "numExtents" : 6,
        "indexes" : 2,
        "indexSize" : 32704,
        "fileSize" : 67108864,
        "nsSizeMB" : 16,
        "extentFreeList" : {
            "num" : 0,
            "totalSize" : 0
        },
        "dataFileVersion" : {
            "major" : 4,
            "minor" : 22
        },
        "ok" : 1
    }

    db.userdatas.stats()
    {
        "ns" : "leyue.userdatas",
        "count" : 11,
        "size" : 1040,
        "avgObjSize" : 94,
        "numExtents" : 1,
        "storageSize" : 8192,
        "lastExtentSize" : 8192,
        "paddingFactor" : 1,
        "paddingFactorNote" : "paddingFactor is unused and unmaintained in 3.0. It  remains hard coded to 1.0 for compatibility only.",
        "userFlags" : 1,
        "capped" : false,
        "nindexes" : 1,
        "totalIndexSize" : 8176,
        "indexSizes" : {
            "_id_" : 8176
        },
        "ok" : 1
    }

View all documents in the collection

    db.Collection name.find();
    db.userdatas.find()
    { "_id" : ObjectId("59789a56bc629e73c4f09e1c"), "name" : "wang wu", "age" : 45 }
    { "_id" : ObjectId("59789a74bc629e73c4f09e1e"), "name" : "wang wu", "age" : 8 }
    { "_id" : ObjectId("59789ac0bc629e73c4f09e20"), "name" : "wang wu", "age" : 33 }
    { "_id" : ObjectId("597f357a09c84cf58880e40e"), "name" : "u1", "age" : 37 }

Documents replace db. Collection name. update (condition, new document); only the first document that meets the requirement is modified.

db.test.update({"age":12},{"address":"Beijing","name":"Lao Wang"})

set: Specifies the value of a field, which is created if it does not exist.

db.test.update({"name":"u1"},{"$set":{"name":"u2"}},0,1)

$unset: Delete a field

db.test.update({"name":"u1"},{"$unset":{"address":1}},0,1)

$push: Add an element to the end of an existing array, and create a new array if not.

db.test.update({"name":"u1"},{"$push":{"score":2}},0,1)

each: Operate multiple values through one push

db.test.update({"name":"u1"},{"$push":{"score":{"$each":[4,5,6]}}})

save method

If the document exists, it will be updated, and if it does not exist, it will be created, which is judged mainly by "_id".

    db.test.save({"name":"li si"})

update

The third parameter, 0, means that the search cannot be found. Document 1 is not added to indicate that the search cannot be found. Documents are added.
The fourth parameter 0 means that only the first 1 is updated to update all the documents found.
1: Can only be used in $XXX operations
2: It's better to specify the fourth parameter of update every time to prevent the server from using default behavior.

find

Find (condition, field shown)

db.userdatas.find({},{name:1,_id:0})

Comparisons: lt,lte,gt,gte,$ne

    db.userdatas.find({age:{$gte:35}})
    30<=age<=35
    db.userdatas.find({age:{$lte:35,$gte:30}})

$and: Contains multiple conditions, and the relationship between them is and

    db.userdatas.find({"name":"u5",age:{$gt:33}})
    db.userdatas.find({$and:[{"name":"u5"},{age:{$gt:33}}]})

$or: Contains multiple conditions, and the relationship between them is or, $nor equals or negative.

     db.userdatas.find({$or:[{"name":"u5"},{age:{$gt:33}}]})

not: Used as a top-level query over other conditions, followed by conditions, regular

    db.userdatas.find({age:{$not:{$lt:35}}})
    db.userdatas.find({name:{$not:/wang/}})

mod: Divide the value of the query by the first given value, and if the remainder equals two values, the match succeeds.

    db.userdatas.find({age:{$mod:[10,7]}})
    db.userdatas.find({age:{$not:{$mod:[10,7]}}})

in: Query multiple values of a key, as long as the key matches one of them. nin is not included.

    db.userdatas.find({age:{$in:[33,35]}})
    db.userdatas.find({age:{$nin:[33,35]}})

$all: The key needs to match all values for the array

    db.userdatas.find({score:{$all:[7,4]}})

Exists: Check whether a key exists, 1 for existence, 0 for nonexistence

    db.userdatas.find({"score":{$exists:1}})

Null type: not only can the value of the matching key be null, but also the case where the matching key does not exist

    db.userdatas.find({score:null})
    db.userdatas.find({name:{$in:[null],$exists:1}})   

regular

    MongoDB uses Perl-compatible regular expressions (PCR E).
    For example: db.users.find({"name": / sishuok/i}); 
    Another example is: db.users.find({"name": /^ sishuok/});

Array search

A single element matches, just like the preceding condition, {key:value}

    db.userdatas.find({score:0})

Multiple elements are matched, using $all, {key:{all:{a, b]}, and the order of elements is indifferent.

    db.userdatas.find({score:{$all:[2,0]}})

Indexes can be used to specify the specific location of the query array, {"key. index number": value}

    db.userdatas.find({"score.0":7}) index starts at 0

Query an array of length, using $size

    db.userdatas.find({"score":{$size:4}})

Specify a subset, using $slice, how many positive numbers are in the front, how many negative numbers are in the tail, and you can also specify a partial number.

Shift and number of elements to return, such as: $slice:[50,10]

    db.userdatas.find({},{"score":{$slice:2}})
    db.userdatas.find({},{"score":{$slice:-2}})
    db.userdatas.find({},{"score":{$slice:[1,1]}})

You can use it to specify any eligible array element, such as: {"users.": 1}

    db.userdatas.find({"score":{$in:[7,4]}},{"score.$":1,name:1})

elemMatch: Requires simultaneous use of multiple conditional statements to compare and judge an array element

    db.userdatas.find({score:{$elemMatch:{$gt:8,$lt:12}}})

Query for embedded documents

1: Querying the entire embedded document is the same as common queries.

2: If you want to specify a key-value match, you can use the "." operator, such as {"name.first":"a", "name.last":"b"}.

3: If you want to specify a set of conditions correctly, you need to use $elemMatch to match multiple keys of embedded documents.

Insert a document:
    db.userdatas.update({"name":"u2"},{$set:{wendang:{"yw":80,"xw":90}}})
Query documents:
     db.userdatas.find({"wendang.yw":80})

The command to query the number of records: count

1. If count() is used directly, the total number of records is obtained.

2. If you want to get the number of entries recorded after a conditional query, you need to specify count(true or non-zero).

    db.userdatas.find().count()
    db.userdatas.find().limit(2).count(true)

Command to limit the number of records returned: limit

    db.userdatas.find().limit(2)

The command to limit the starting point of the number of records returned: skip (from which entry to return)

    db.userdatas.find().skip(0).limit(2)

Sort command: sort({field to be sorted: 1 in ascending order and - 1 in descending order})

    db.userdatas.find().sort({age:-1})  
    db.userdatas.find().sort({age:-1}).limit(2)

paging

Paging queries: combination of limit,skipt and sort skip is inefficient
Of course, there are other ways to paginate, such as using a custom id, and then paging according to ID.

Query all non-repetitive data for a given key, command: distinct

     Syntax: db.runCommand({"distinct": collection name, "key":"get the field of non-repetitive data"});
     db.runCommand({"distinct":"userdatas","key":"age"})

     db.runCommand({"distinct":"userdatas","key":"age"})
    {
        "waitedMS" : NumberLong(0),
        "values" : [
            45,
            8,
            33,
            37,
            78,
            32,
            30,
            20
        ],
        "stats" : {
            "n" : 11,
            "nscanned" : 0,
            "nscannedObjects" : 11,
            "timems" : 0,
            "planSummary" : "COLLSCAN"
        },
        "ok" : 1
    }

cursor

1: Get the cursor as follows:

var c = db.users.find();

2: Circular cursors, which can be set, are illustrated as follows:

   while(c.hasNext()){
         printjson(c.next().Document key);
} 

3: forEach can also be used to loop, as shown below.

   c.forEach(function(obj){
         print(obj);
}); 

Topics: Database MongoDB Javascript shell