mongodb的一些内容


mongodb:

主要出自下面的mongodb manual,这里只是个人看的时候画出的部分。

目前关注点还是在使用上,mongodb的实现机制还要继续学习,不是分分钟能解决的事情。

下面的这堆有种瞎记笔记的感觉,等之后在整理成中文吧。

https://docs.mongodb.com/manual

另有中文manual:

http://docs.mongoing.com/manual-zh/


BSON:

http://bsonspec.org/

BSON [bee · sahn], short for Bin­aryJSON, is a bin­ary-en­coded seri­al­iz­a­tion of JSON-like doc­u­ments. Like JSON, BSON sup­ports the em­bed­ding of doc­u­ments and ar­rays with­in oth­er doc­u­ments and ar­rays. BSON also con­tains ex­ten­sions that al­low rep­res­ent­a­tion of data types that are not part of the JSON spec. For ex­ample, BSON has a Date type and a BinData type.

BSON is a binary format in which zero or more key/valuepairs are stored as a single entity. We call this entityadocument.

BSON is designed to be efficient in space, but in some cases is not much more efficient than JSON. In some cases BSON uses even more space than JSON. The reason for this is another of the BSON design goals: traversability. BSON adds some "extra" information to documents, like length of strings and subobjects. This makes traversal faster.

BSON is also designed to be fast to encode and decode. For example, integers are stored as 32 (or 64) bit integers, so they don't need to be parsed to and from text. This uses more space than JSON for small integers, but is much faster to parse.

In addition to compactness, BSON adds additional data types unavailable in JSON, notably the BinData and Date data types.


mongo shell




New in version 3.2.

By default, a collection does not require its documents to have thesame schema; i.e. the documents in a single collection do not need tohave the same set of fields and the data type for a field can differacross documents within a collection.

Starting in MongoDB 3.2, however, you can enforce documentvalidation rules for a collection duringupdate and insert operations. SeeDocument Validation fordetails.



MMAPv1 is MongoDB’s original storage engine based on memory mappedfiles. It excels at workloads with high volume inserts, reads, andin-place updates.

Changed in version 3.2: Starting in MongoDB 3.2, the MMAPv1 is no longer the default storageengine; instead, theWiredTiger storageengine is the default storage engine . SeeDefault Storage Engine Change.

In order to ensure that all modifications to a MongoDB data set aredurably written to disk, MongoDB, by default, records all modificationsto an on-disk journal. MongoDB writes more frequently to the journalthan it writes the data files.

In the default configuration for the MMAPv1 storage engine, MongoDB writes to the data files on disk every 60seconds and writes to thejournal files roughly every 100milliseconds.

The journal allows MongoDB to successfully recover data from data filesafter a mongod instance exits without flushing all changes.See Journaling for more information about the journal inMongoDB.



BSON is a binary serialization format used to store documentsand make remote procedure calls in MongoDB. The BSON specification islocated at bsonspec.org.

  1. MinKey (internal type)
  2. Null
  3. Numbers (ints, longs, doubles)
  4. Symbol, String
  5. Object
  6. Array
  7. BinData
  8. ObjectId
  9. Boolean
  10. Date
  11. Timestamp
  12. Regular Expression
  13. MaxKey (internal type)

MongoDB sorts BinData in the following order:

  1. First, the length or size of the data.
  2. Then, by the BSON one-byte subtype.
  3. Finally, by the data, performing a byte-by-byte comparison.
BSON strings are UTF-8.

Given strings using UTF-8character sets, using sort() on stringswill be reasonably correct. However, because internallysort() uses the C++ strcmp api, thesort order may handle some characters incorrectly.

var mydoc = {
               _id: ObjectId("5099803df3f4948bd2f98391"),
               name: { first: "Alan", last: "Turing" },
               birth: new Date('Jun 23, 1912'),
               death: new Date('Jun 07, 1954'),
               contribs: [ "Turing machine", "Turing test", "Turingery" ],
               views : NumberLong(1250000)
            }

  • The field name _id is reserved for use as a primary key; itsvalue must be unique in the collection, is immutable, and may be ofany type other than an array.
  • The field names cannot start with the dollar sign ($) character.
  • The field names cannot contain the dot (.) character.
  • The field names cannot contain the null character.

The _id field may contain values of anyBSON data type, other than an array.

To specify or access a field of an embedded document with dot notation,concatenate the embedded document name with the dot (.) andthe field name, and enclose in quotes:


db.users.find( { badges: [ "blue", "black" ] } )

The query matches the following document:

{
   "_id" : 1,
   "name" : "sue",
   "age" : 19,
   "type" : 1,
   "status" : "P",
   "favorites" : { "artist" : "Picasso", "food" : "pizza" },
   "finished" : [ 17, 3 ]
   "badges" : [ "blue", "black" ],
   "points" : [ { "points" : 85, "bonus" : 20 }, { "points" : 85, "bonus" : 10 } ]
}

Match an Array Element

Equality matches can specify a single element in the array to match.These specifications match if the array contains at leastone elementwith the specified value.

The following example queries for all documents where badges is anarray that contains "black" as one of its elements:

db.users.find( { badges: "black" } )

The query matches the following documents:

{
   "_id" : 1,
   "name" : "sue",
   "age" : 19,
   "type" : 1,
   "status" : "P",
   "favorites" : { "artist" : "Picasso", "food" : "pizza" },
   "finished" : [ 17, 3 ]
   "badges" : [ "blue", "black" ],
   "points" : [ { "points" : 85, "bonus" : 20 }, { "points" : 85, "bonus" : 10 } ]
}

db.users.find( { "badges.0": "black" } )

The operation returns the following document:

{
   "_id" : 6,
   "name" : "abc",
   "age" : 43,
   "type" : 1,
   "status" : "A",
   "favorites" : { "food" : "pizza", "artist" : "Picasso" },
   "finished" : [ 18, 12 ],
   "badges" : [ "black", "blue" ],
   "points" : [ { "points" : 78, "bonus" : 8 }, { "points" : 57, "bonus" : 7 } ]
}

The following example queries for documents where the finished arraycontains elements that in some combination satisfy the queryconditions; e.g., one element can satisfy the greater than15condition and another element can satisfy the less than20condition, or a single element can satisfy both:

db.users.find( { finished: { $gt: 15, $lt: 20 } } )

Use $elemMatch operator to specify multiple criteria on theelements of an array such that at least one array element satisfies allthe specified criteria. 

The following example queries for documents where the finished arraycontains at least one element that is greater than ($gt)15and less than ($lt)20:

db.users.find( { finished: { $elemMatch: { $gt: 15, $lt: 20 } } } )

The following example selects all documents where the pointscontains an array whose first element (i.e. index is0) is adocument that contains the fieldpoints whose value is less thanor equal to55:

db.users.find( { 'points.0.points': { $lte: 55 } } )

The following example selects all documents where the points is anarray with at least one embedded document that contains the fieldpoints whose value is less than or equal to55:

db.users.find( { 'points.points': { $lte: 55 } } )

The operation returns the following documents:

{
   "_id" : 3,
   "name" : "ahn",
   "age" : 22,
   "type" : 2,
   "status" : "A",
   "favorites" : { "artist" : "Cassatt", "food" : "cake" },
   "finished" : [ 6 ],
   "badges" : [ "blue", "red" ],
   "points" : [ { "points" : 81, "bonus" : 8 }, { "points" : 55, "bonus" : 20 } ]
}

The following example queries for documents where the points arraycontains elements that in some combination satisfy the queryconditions; e.g. one element satisfies thepoints less than orequal to70 condition and another element satisfies thebonusequal to 20 condition, or a single element satisfies bothcriteria:

db.users.find( { "points.points": { $lte: 70 }, "points.bonus": 20 } )
数组的查询,里面‘,’表示的含义和键值对查询‘,’表示and不一样;

NameDescription
$eqMatches values that are equal to a specified value.
$gtMatches values that are greater than a specified value.
$gteMatches values that are greater than or equal to a specified value.
$ltMatches values that are less than a specified value.
$lteMatches values that are less than or equal to a specified value.
$neMatches all values that are not equal to a specified value.
$inMatches any of the values specified in an array.
$ninMatches none of the values specified in an array.


NameDescription
$orJoins query clauses with a logical OR returns all documents that match the conditions of either clause.
$andJoins query clauses with a logical AND returns all documents that match the conditions of both clauses.
$notInverts the effect of a query expression and returns documents that do not match the query expression.
$norJoins query clauses with a logical NOR returns all documents that fail to match both clauses.

NameDescription
$existsMatches documents that have the specified field.
$typeSelects documents if a field is of the specified type.

NameDescription
$modPerforms a modulo operation on the value of a field and selects documents with a specified result.
$regexSelects documents where values match a specified regular expression.
$textPerforms text search.
$whereMatches documents that satisfy a JavaScript expression.
NameDescription
$geoWithinSelects geometries within a bounding GeoJSON geometry. The 2dsphere and 2d indexes support$geoWithin.
$geoIntersectsSelects geometries that intersect with a GeoJSON geometry.The 2dsphere index supports$geoIntersects.
$nearReturns geospatial objects in proximity to a point.Requires a geospatial index. The2dsphere and 2d indexes support$near.
$nearSphereReturns geospatial objects in proximity to a point on a sphere.Requires a geospatial index. The2dsphere and 2d indexes support$nearSphere.

NameDescription
$allMatches arrays that contain all elements specified in the query.
$elemMatchSelects documents if element in the array field matches all the specified $elemMatch conditions.
$sizeSelects documents if the array field is a specified size.
NameDescription
$bitsAllSetMatches numeric or binary values in which a set of bit positions all have a value of1.
$bitsAnySetMatches numeric or binary values in which any bit from a set of bit positions has a value of1.
$bitsAllClearMatches numeric or binary values in which a set of bit positions all have a value of0.
$bitsAnyClearMatches numeric or binary values in which any bit from a set of bit positions has a value of0.
NameDescription
$commentAdds a comment to a query predicate.
NameDescription
$Projects the first element in an array that matches the query condition.
$elemMatchProjects the first element in an array that matches the specified $elemMatch condition.
$metaProjects the document’s score assigned during $text operation.
$sliceLimits the number of elements projected from an array. Supports skip and limit slices.

The following example adds a $comment to afind() operation :

db.records.find(
   {
     x: { $mod: [ 2, 0 ] },
     $comment: "Find even values."
   }
)

db.posts.find( {}, { comments: { $slice: 5 } } )

Here, $slice selects the first five items in an arrayin thecomments field.

db.posts.find( {}, { comments: { $slice: -5 } } )

This operation returns the last five items in array.


db.collection.find( { field: { $size: 2 } } );
returns all documents in collection where field is an arraywith 2 elements. For instance, the above expression willreturn { field:[ red, green] } and { field: [apple,lime ]} but not {field: fruit } or { field: [orange, lemon, grapefruit ] }.


The following query specifies a $search string ofcoffee:

db.articles.find( { $text: { $search: "coffee" } } )

This query returns the documents that contain the term coffee in theindexed subject field, or more precisely, the stemmed version ofthe word:

{ "_id" : 2, "subject" : "Coffee Shopping", "author" : "efg", "views" : 5 }
{ "_id" : 7, "subject" : "coffee and cream", "author" : "efg", "views" : 10 }
{ "_id" : 1, "subject" : "coffee", "author" : "xyz", "views" : 50 }

The following query specifies a $search string of three termsdelimited by space,"bake coffeecake":

db.articles.find( { $text: { $search: "bake coffee cake" } } )

This query returns documents that contain either bake orcoffeeor cake in the indexedsubject field, or moreprecisely, the stemmed version of these words:

{ "_id" : 2, "subject" : "Coffee Shopping", "author" : "efg", "views" : 5 }
{ "_id" : 7, "subject" : "coffee and cream", "author" : "efg", "views" : 10 }
{ "_id" : 1, "subject" : "coffee", "author" : "xyz", "views" : 50 }
{ "_id" : 3, "subject" : "Baking a cake", "author" : "abc", "views" : 90 }
{ "_id" : 4, "subject" : "baking", "author" : "xyz", "views" : 100 }

The following query searches for the phrase coffeeshop:

db.articles.find( { $text: { $search: "\"coffee shop\"" } } )

This query returns documents that contain the phrase coffee shop:

{ "_id" : 2, "subject" : "Coffee Shopping", "author" : "efg", "views" : 5 }

The following example searches for documents that contain the wordscoffee but donot contain the term shop, or more preciselythe stemmed version of the words:

db.articles.find( { $text: { $search: "coffee -shop" } } )

The following query performs a case and diacritic insensitive textsearch for the termsсы́рники or CAFÉS:

db.articles.find( { $text: { $search: "сы́рники CAFÉS" } } )

The following query specifies es, i.e. Spanish, as the languagethat determines the tokenization, stemming, and stop words:

db.articles.find(
   { $text: { $search: "leche", $language: "es" } }
)

The following query performs a case sensitive search for the termCoffee:

db.articles.find( { $text: { $search: "Coffee", $caseSensitive: true } } )

The following query performs a diacritic sensitive text search on theterm CAFÉ, or more precisely the stemmed version of the word:

db.articles.find( { $text: { $search: "CAFÉ", $diacriticSensitive: true } } )

The following query searches for the term cake and returns thescore assigned to each matching document:

db.articles.find(
   { $text: { $search: "cake" } },
   { score: { $meta: "textScore" } }
)

The returned document includes an additional field score thatcontains the document’s score associated with the text search.[1]

To sort by the text score, include the same $metaexpression inboth the projection document and the sort expression.[1] The following query searches for the term coffeeand sorts the results by the descending score:

db.articles.find(
   { $text: { $search: "coffee" } },
   { score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } )

The query returns the matching documents sorted by descending score.

Use the limit() method in conjunction with asort() to return the top n matching documents.

The following query searches for the term coffee and sorts theresults by the descending score, limiting the results to the top twomatching documents:

db.articles.find(
   { $text: { $search: "coffee" } },
   { score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } ).limit(2)
SQL Terms/ConceptsMongoDB Terms/Concepts
databasedatabase
tablecollection
rowdocument orBSON document
columnfield
indexindex
table joinsembedded documents and linking

primary key

Specify any unique column or column combination as primarykey.

primary key

In MongoDB, the primary key is automatically set to the_id field.

aggregation (e.g. group by)

aggregation pipeline

See the SQL to Aggregation Mapping Chart.


Diagram of the annotated aggregation pipeline operation. The aggregation pipeline has two stages: ``$match`` and ``$group``.


mongodb的几个可执行文件:

mongodump

mongorestore

mongoimport

mongoexport

mongo

mongod

具体命令规则待之后补充。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值