mongodb的一些内容

发布时间:2017-2-26 10:48:03编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"mongodb的一些内容",主要涉及到mongodb的一些内容方面的内容,对于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.SeeJournaling 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不一样;

Name Description
$eq Matches values that are equal to a specified value.
$gt Matches values that are greater than a specified value.
$gte Matches values that are greater than or equal to a specified value.
$lt Matches values that are less than a specified value.
$lte Matches values that are less than or equal to a specified value.
$ne Matches all values that are not equal to a specified value.
$in Matches any of the values specified in an array.
$nin Matches none of the values specified in an array.


Name Description
$or Joins query clauses with a logical OR returns all documents that match the conditions of either clause.
$and Joins query clauses with a logical AND returns all documents that match the conditions of both clauses.
$not Inverts the effect of a query expression and returns documents that do not match the query expression.
$nor Joins query clauses with a logical NOR returns all documents that fail to match both clauses.

Name Description
$exists Matches documents that have the specified field.
$type Selects documents if a field is of the specified type.

Name Description
$mod Performs a modulo operation on the value of a field and selects documents with a specified result.
$regex Selects documents where values match a specified regular expression.
$text Performs text search.
$where Matches documents that satisfy a JavaScript expression.
Name Description
$geoWithin Selects geometries within a bounding GeoJSON geometry. The 2dsphere and 2d indexes support$geoWithin.
$geoIntersects Selects geometries that intersect with a GeoJSON geometry.The 2dsphere index supports$geoIntersects.
$near Returns geospatial objects in proximity to a point.Requires a geospatial index. The2dsphere and 2d indexes support$near.
$nearSphere Returns geospatial objects in proximity to a point on a sphere.Requires a geospatial index. The2dsphere and 2d indexes support$nearSphere.

Name Description
$all Matches arrays that contain all elements specified in the query.
$elemMatch Selects documents if element in the array field matches all the specified $elemMatch conditions.
$size Selects documents if the array field is a specified size.
Name Description
$bitsAllSet Matches numeric or binary values in which a set of bit positions all have a value of1.
$bitsAnySet Matches numeric or binary values in which any bit from a set of bit positions has a value of1.
$bitsAllClear Matches numeric or binary values in which a set of bit positions all have a value of0.
$bitsAnyClear Matches numeric or binary values in which any bit from a set of bit positions has a value of0.
Name Description
$comment Adds a comment to a query predicate.
Name Description
$ Projects the first element in an array that matches the query condition.
$elemMatch Projects the first element in an array that matches the specified $elemMatch condition.
$meta Projects the document’s score assigned during $text operation.
$slice Limits 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 wherefield 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/Concepts MongoDB Terms/Concepts
database database
table collection
row document orBSON document
column field
index index
table joins embedded 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

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





上一篇:详解ROC/AUC计算过程
下一篇:IIS与tomcat共用80端口方法3

相关文章

相关评论

本站评论功能暂时取消,后续此功能例行通知。

一、不得利用本站危害国家安全、泄露国家秘密,不得侵犯国家社会集体的和公民的合法权益,不得利用本站制作、复制和传播不法有害信息!

二、互相尊重,对自己的言论和行为负责。

最近更新

好贷网好贷款