Thursday, December 19, 2019

MongoDB in Action Note 2

MongoDB in Action Note
1.
Indexes in MongoDB are implemented as a B-tree data structure.
With MongoDB, you can create up to 64 indexes per collection. The kinds of
indexes supported include all the ones you’d find in an RDMBS; ascending, descending,
unique, compound-key, hashed, text, and even geospatial indexes4 are supported.
2.
mongoexport and mongoimport—Export and import JSON, CSV, and TSV7 data;
3.
db.users.insert({username: "smith"})
db.users.find()
db.users.find({username: "jones"})
db.users.find().pretty()
db.users.count()
db.users.update({username: "smith"}, {$set: {country: "Canada"}})   --OPERATOR UPDATE
db.users.update({username: "smith"}, {country: "Canada"})           --REPLACEMENT UPDATE
db.foo.remove()
db.users.remove({"favorites.cities": "Cheyenne"})
db.users.drop()
4.
> help
> db.help()
$ mongo --help
5.
> for(i = 0; i < 20000; i++) {
db.numbers.save({num: i});
}
db.numbers.find( {num: {"$gt": 20, "$lt": 25 }} )
db.numbers.find({num: {"$gt": 19995}}).explain("executionStats")
db.numbers.createIndex({num: 1})
db.numbers.getIndexes()
db.numbers.find({num: {"$gt": 19995 }}).explain("executionStats")
> db.stats() (wraps db.runCommand( {dbstats: 1} ) )
you can execute the parentheses-less version and see the internals:
> db.runCommand
6.
In addition to the size limit, MongoDB allows you to specify a maximum number
of documents for a capped collection with the max parameter.
MongoDB also allows you to expire documents from a collection after a certain
amount of time has passed. These are sometimes called time-to-live (TTL) collections.
7.
BSON specifies three numeric types: double, int, and long.
The BSON datetime type is used to store temporal values. Time values are represented
using a signed 64-bit integer marking milliseconds since the Unix epoch.
if you’re creating dates in JavaScript, keep in mind that months in JavaScript dates are 0-based.
8.
db.stockdata.find({code: "SH600050"}).skip(3490).limit(3).sort({'date':1}).pretty()
MongoDB allows you to query using regular expressions
db.users.find({'last_name': /^Ba/})
db.users.find({'first_name': "Smith", birth_year: 1975})
db.reviews.find({
'user_id': ObjectId("4c4b1476238d3b4dd5000001"),
'$where': "(this.rating * .92) > 3"
})
9.
Projections:
db.users.find({}, {'username': 1}) --returns user documents excluding all but two fields: the username and the _id field
db.users.find({}, {'addresses': 0, 'payment_methods': 0})  --returns user documents including all exclude the two fields
To return the first 12 reviews,
or the last 5, you’d use $slice like this:
db.products.find({}, {'reviews': {$slice: 12}})
db.products.find({}, {'reviews': {$slice: -5}})
10.
Aggregation pipeline operations include the following:
$project—Specify fields to be placed in the output document (projected).
$match—Select documents to be processed, similar to find().
$limit—Limit the number of documents to be passed to the next step.
$skip—Skip a specified number of documents.
$unwind—Expand an array, generating one output document for each array entry.
$group—Group documents by a specified key.
$sort—Sort documents.
$out—Write the results of the pipeline to a collection
$redact—Control access to certain data
11.
db.stockdata.aggregate([{$group:{_id:'$code',count:{$sum:1}}}]);
db.stockdata.aggregate([
{$match:{'code':/^SH/}},
{$group:{_id:'$code',count:{$sum:1}}}
]);
db.stockdata.aggregate([
{$match:{'code':/^SH/}},
{$group:{
_id:'$code',
average:{$avg:'$close'},
count:{$sum:1}
}}
]);
db.stockdata.aggregate([
{$match:{'code':/^SH/}},
{$group:{
_id:'$code',
average:{$avg:'$close'},
count:{$sum:1}
}}
]).forEach(function(doc){
var category = db.stockdata.findOne({code:doc._id});
if(category!=null){
doc.code = category.code;
}
else{
doc.code = 'not found';
}
db.mainStockData.insert(doc);
});

No comments:

Post a Comment