MongoDB Common Commands

Source: Internet
Author: User
Tags findone mongodb unique id

MongoDB has been used recently in new projects, so it took some time to learn a bit. This article to their own study to make a summary, intends to use this article as an API in the future, but also to some ready to learn the small partners, hoping to help you.
Date:2018-04-25 20:49:12

MongoDB Common Commands

MongoDB has been used recently in new projects, so it took some time to learn a bit. This article to make a summary of their own learning, by the way, the article as an API to use, but also to share some of the preparation of learning partners, hope to help you.

Basic knowledge
    • The default database name used by MONGO is test. If no database is created, then the data for the collection and operation is saved in the test database.
    • The data in MONGO is expressed in the document format of the class JSON, which is called "Bson" in Mongo, and I will replace it with "document".
    • MONGO corresponds to MySQL data set:
      • Db=database, the database has nothing to say.
      • Table=collection, in Mongo, the collection is somewhat similar to the concept of a table.
      • There is a big difference between the fields in the MONGO, the MONGO field is not determined according to the collection setting, and is based on the data. For example, there are two of the following data in the same collection:
      {"_id":1,"name":"Bob","age":18}{"_id":2,"city":"北京"}
      The field you see in the visualizer may be _id, name, age, city, except that the first data city is empty, the second data name and age are empty, but this is not the case, to say two of the data separate understanding, they simply belong to the same aggregation, The data retrieved by Collection.find ("_id": 1) does not contain the name and age, a bit like a two-dimensional array, and each dimension's array (data) is independent.
Database collection Operations
    • Use database_name
      Cases:use mydb
      You will be redirected to a database named MyDB, and if the database does not exist, create the database.
    • Db
      View the currently selected database
    • Show DBS
      View the list of databases
    • Db.dropdatabase ()
      Delete current Database
    • Db.collections.drop ()
      Delete Current Collection
New (Create)
    • Insert
      db.COLLECTION_NAME.insert(document)
      If you do not specify _id, a randomly unique ID is automatically generated, and multiple records can be inserted using the
      db.COLLECTION_NAME.insert([doucument,document])
      Cases:
db.col.insert({    title: 'MongoDB',by: 'bfsan',tags:['mongodb', 'database', 'NoSQL'],likes: 100})  

There are also Inserone () and Insermany (), which use these two methods to return the ID value of the inserted document, using the same usage as insert.

Updates (update)
    • Update
db.collection.update(    <query>,    <update>,    {        upsert: <boolean>,//true则对于不存在对应情况的记录会新增,存在则会修改        multi: <boolean>,//true则会修改多条记录        writeConcern: <document>//(可选)写安全,用的不多,详细内容请再查询    })

Cases:

db.col.update( { "count" : { $gt : 15 } } , { $inc : { "count" : 1} },false,true );//对count>15的所有记录,count=count+1db.col.update( { "count" : { $gt : 4 } } , { $set : { "test5" : "OK"} },true,false );//对查询是否存在count>4的记录,存在则为查到的第一条记录(增加/修改)test5=OK,不存在则增加一条test5=OK的记录
    • Save
db.collection.save(    <document>,    {writeConcern: <document>})

The Save method replaces the existing document by passing in the document, and if the ID is not specified, it is added, the ID is automatically assigned, and if _ID is specified, all data for the record containing the _id is replaced.

Remove (delete)
    • Delete
db.collection.remove(    <query>,//当条件为空时,则清空该collection    {        justOne: <boolean>, //true或1,则只删除第一个文档        writeConcern: <document>    })
Query (Retrieve)
    • Find
db.collection.find(<query>, <projection>)//query条件,省略则查询所有;projection投影出指定的列,省略则显示所有列
Query criteria
function Grammar
Equals {Key:value}
Less than {key:{$lt: value}}
Less than or equal to {key:{$lte: value}}
Greater than {key:{$gt: value}}
Greater than or equal to {key:{$gte: value}}
Not equal to {key:{$ne: value}}
and {key1:value1, key2:value2}
Or {$or: [{key1:value1},{key2:value2}]}
Not {key:{$not: value}}
Inch {key:{$in: array}}
Not in {key:{$nin: array}}
All {key:{$all: array}}
Whether there is {key:{$exists: True/false}}
Records that match a data type {key:{$type: type}}
Result processing
.pretty()       //格式化结果显示,使结果格式自动缩进符合规范。.limit(n)       //显示前n条记录.skip(n)        //跳过前n条记录.sort({key:1/-1})   //排序,1升序,-1降序

Note: When querying with Sort,skip,limit at the same time, the execution order is always sort-skip-limit, regardless of the call sequence.

Connection Query
    • You must use the FindOne method to store the variables in transit
var result = db.users.findOne({"name":"Tom Benzamin"},{"address_ids":1})var addresses = db.address.find({"_id":{"$in":result["address_ids"]}})
    • $lookup Instructions
      MONGO provides the left outer join query in the syntax format
      $lookup:{from,localField,foreignField,as}
      You need to use the aggregate command to manipulate the format
      db.COLLECTION_NAME.aggreate({$lookup:{from,localField,foreignField,as}})
      • From, the collection name to associate with
      • Localfield, "foreign Key" in this collection
      • Foreignfield, the field in the collection to associate with
      • As, the field name to which the output connected document is to
Polymerization
db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)常用操作:    {$project:{key:1/0}}    修改输入文档的结构。可以用来重命名、增加或删除字段,也可以用于创建计算结果以及嵌套文档。    {$match:{query}}    用于过滤数据,只输出符合条件的文档。    {$limit:n}      用来限制返回的文档数。    {$skip:n}       在跳过指定数量的文档。    {$sort:{key:1/-1}}  将文档排序后输出。    $group          将集合中的文档分组,可用于统计结果。
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.