MongoDB Common basic operations

Source: Internet
Author: User
Tags array length findone

First, the basic

MongoDB does not need to explicitly create a database like a relational database, and can be created directly using the USE statement:

>  use foo

Insert a document into the collection using the Insert method:

> db.blog. Insert (POST)

Find using the Find or FindOne method:

> Db.blog.find () > db.blog.findOne ()

The update uses the Update method, which accepts two parameters. The first parameter is used for positioning, and the second parameter passes the updated document. Before this, you need to use the Var method to remove the original record:

 >  var  updatedpost =  db.blog.findOne ({"   Title   ": "   Post   " })    updatedpost.content =   " new Content   " >  Db.blog. update  ({ " title  "  :  " post  "  }, Updatedpost) 

Remove using the Remove method:

> db.blog.remove ({'title':'Post'})

II. Create, update, and delete

1. Batch creation:

> db.batchinsert ([{' A ': 1}, {' A ': 2}, {' A ': 3}])

2. Modifier

$inc: Increase in value

> db.data. Update ({'_id':1}, {'$inc ': {'times': 1}}) 

$set: Specify field values

> db.data. Update ({'_id':1}, {'$set': {'title ':'new title'}})

$unset: Delete a field

> db.data. Update ({'_id:1'}, {'$unset': {'title' :1}})

$push: Add a field, save the value of the new field to an array to add to the document

> db.data. Update ({'_id:1'}, {'$push': {'comments' :'comment1'}})

$addToSet and $each combinations: add multiple different values and no longer add if they already exist

> db.data. Update ({'_id':1}, {'$addToSet': {'Email  ': {'$each'[' [email protected] ', ' [email Protected] ', ' [email protected] '}}})

$pull: Deletes a specific element, deleting an element of value in the array only if the value of key is available for the group

> Db.blog. Update ({}, {'$pull': {'key':'value'}} )

$ locator: Used to locate and modify documents that meet the requirements. Here $ is used instead of the found comment in the array where John is located and updated with $set

> db.blog. Update ({'comment.author':'John'}, {'$set  ': {'comment.$.author':'Jack'}}

3. Using Upsert

Upsert can be created for elements that do not exist, and do not operate on elements that already exist. In update, in the third parameter, change it to true.

> db.collection. Update ({'key':3}, {'$inc': {'key ':1}}, True)

If a document with key 3 exists in the collection, the operation changes the value of key 3 to 4, and if it does not, a document with key 4 is created. In addition, if you do this again, a document with key 4 will be generated again.

4. Update more than one document

The 4th parameter of the Update method controls whether more than one qualifying record is updated. Set to TRUE to update multiple matching records and set to False to update only one matching record.

Third, find

Find using Find or FindOne (find a record). If you want to return only a specific number of fields, you can do the following:

> db.blog.find ({}, {'username'1'post' 1})

This will include only the username and post fields in the output. However, the _id field is returned by default and needs to be manually specified as 0 in the Find parameter to not return.

1. Comparison operators

$lt, $GT, $lte, $gte, $ne corresponding to the <, >, <=, >=,! = Five comparison operators, you can do the following:

> db.collection.find ({'score': {'$gte'60  '$lte'

This allows you to find a record of fractions between 60 and 70.

2. $or, $in

$or used to select the criteria to satisfy a single bar. $in used for value selection to determine whether the value is within an array.

> db.collection.find ({'number': {'$in'[  1, 2, 3]})> db.collection.find ({'$or')  [{' number ': 1}, {' Age ':'} '}]

Similarly, there are $nin, $not and $and.

3. $exists

$exists used to determine whether a field exists. True for existence, false for non-existent. The following action is used to look for a record with a value of NULL:

> db.collection.find ({'key': {'$in'[ NULL ]'$exists': True}})

There is no equal operator, so use in instead. If you do not add the following exists operator, all records that have a value of NULL and that the key field does not exist are returned.

4. Array Lookup

Finds array matches with $all through multiple elements. The following operation finds the value of key containing an array of value1 and value2.

> db.collection.find ({'key': {'$all'[ ' value1 ', ' value2 ' ]}})

If $all is not added, it becomes an exact match. If you want to find the element by location, you need to add a subscript to the key.

> db.collection.find ({'key.0'value1' 

In addition, the array length can be queried using $size.

> db.collection.find ({'key': {'$size'3 }})

You can query some elements of an array using $slice. The following operation returns 5 elements from the array starting with number 5th.

> db.collection.find ({'author':'John'}, {'  Comment': {'$slice'[5, 5] 

5. Querying inline documents

Matches some elements of a document with $elemmatch. The following action is used to find the author's 5 comment for John, and if you do not add Elemmatch, you cannot match if there are other key-value pairs in the document.

> db.post.find ({'comment': {'$elemMatch': {  'author'John'score' 5}})

6. Result processing

$limit the number of limit results, $skip skip partial results and $sort sort the results.

> db.collection.limit (3)> db.collection.skip (3)  > db.collection.sort ({'_id'1'key'  -1})

MongoDB Common basic operations

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.