Mongodb Basic Usage

Posted by alex.hughson on Wed, 03 Jul 2019 19:15:00 +0200

SQL Terms/Concepts MongoDB Terms/Concepts Explanation/Explanation
database database data base
table collection Database tables/collections
row document Data Record Row/Document
column field Data Fields/Fields
index index Indexes
table joins Table connection, not supported by MongoDB
primary key primary key Primary key, MongoDB automatically sets the _id field as the primary key

Create Delete Database

1. Create a database

use DATABASE_NAME

2. View the database

show dbs

3. Delete the current database

db.dropDatabase()

4. Delete Collection

db.collectionName.drop()

CRUD operations for documents

The data structure of the document is basically the same as JSON.

All data stored in the collection is in BSON format.

BSON is a binary storage format like json, referred to as Binary JSON.

1. Insert the document insert() or save()

db.COLLECTION_NAME.insert(document)

2. Update the document update(), save()

update():

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
   }
)

Query: The query criteria for update, similar to those behind where in sql update queries.

Update: update object and some updated operators (e.g. $, $inc...)And so on, which can also be interpreted as following set in sql update query

upsert: Optional. This parameter means whether to insert objNew if no update record exists, true is insert, false by default, and no insert.

multi: Optional, mongodb defaults to false, updates only the first record found, and if this parameter is true, updates all records found on condition.

WritteConcern: Optional, the level at which the exception was thrown.

save() method replaces an existing document with an incoming document

db.collection.save(
   <document>,
   {
     writeConcern: <document>
   }
)

document: document data.

WritteConcern: Optional, the level at which the exception was thrown.

3. Delete the document remove()

db.collection.remove(
   <query>,
   {
     justOne: <boolean>,
     writeConcern: <document>
   }
)

query: (optional) The condition for deleting the document.

justOne: (optional) If set to true or 1, only one document will be deleted.

WteConcern: (optional) The level at which an exception was thrown.

4. Query document find()

db.collection.find(query, projection)

Query: optional, use query operators to specify query conditions

Projection: Optional, use the projection operator to specify the returned key.Returns all the key values in the document when querying, simply omitting the parameter (omitted by default)

query criteria

$lt,$lte,$gt,$gte corresponds to <, <=, >, >=

AND condition

Multiple keys can be passed in, each separated by a comma

db.col.find({key1:value1, key2:value2}).pretty()

OR condition

Keyword $or:

db.col.find(
   {
      $or: [
         {key1: value1}, {key2:value2}
      ]
   }
).pretty()

$type operator

The $type operator retrieves the matching data types in the collection based on the BSON type and returns the results.

db.col.find({"title" : {$type : 2}})

limit() and skip() methods

The limit() method accepts a numeric parameter that specifies the number of records read from MongoDB.

db.COLLECTION_NAME.find().limit(NUMBER)

The skip method also accepts a numeric parameter as the number of records skipped.

db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)

The first {} place where condition, which is empty, returns all documents in the collection.
The second {} specifies which columns are displayed and not displayed (0 means no display 1 means display)

db.col.find({},{"title":1,_id:0}).limit(2)

sort() method

The sort() method specifies the field to sort by a parameter and uses 1 and -1 to specify the sort method, where 1 is in ascending order and -1 is in descending order.

db.COLLECTION_NAME.find().sort({KEY:1})

Indexes

  1. Create index ensureIndex({key:0/1})
db.COLLECTION_NAME.ensureIndex({KEY:1})

The Key value is the index field you want to create, 1 specifies to create the index in ascending order, and -1 if you want to create the index in descending order

ensureIndex() receives optional parameters, which are listed as follows:

The background Boolean indexing process can block other database operations, and backgrounds can specify background indexing by adding an optional "background" parameter."Background" defaults to false.

Is the index created by unique Boolean unique?Specifies that a unique index is created for true.The default value is false.

The name of the name string index.If not specified, MongoDB generates an index name by joining the field names and sort order of the index.

Whether dropDups Boolean deletes duplicate records when building a unique index, specifying true to create a unique index.The default value is false. 

Sparse Boolean does not index field data that does not exist in the document; this parameter requires special attention that if set to true, documents that do not contain corresponding fields will not be queried in the index field.The default value is false. 

ExpireAfterSeconds integer specifies a number in seconds to complete the TTL settings and set the lifetime of the collection. 

The version number of the V index version index.The default index version depends on the version that mongod runs when it creates the index. 

The weights document index weight value, which is between 1 and 99,999, represents the index's score weight relative to other index fields. 

Default_language string For text indexes, this parameter determines the list of rules for deactivation and stemming and word organs.Default to English 

Language_override string For a text index, this parameter specifies the field name contained in the document. The language overrides the default language and the default value is language. 

aggregate()

It is mainly used to process data (such as statistical mean, sum, etc.) and return the calculated data results.It's a bit like count(*) in an sql statement.

db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
> db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])
{
   "result" : [
      {
         "_id" : "w3cschool.cc",
         "num_tutorial" : 2
      },
      {
         "_id" : "Neo4j",
         "num_tutorial" : 1
      }
   ],
   "ok" : 1
}
>

Aggregated expression:

Expression describe
$sum Calculate the sum.
$avg Calculate mean
$min Gets the minimum value corresponding to all documents in the collection.
$max Gets the maximum corresponding value of all documents in the collection
$push Insert values into an array in the result document
$addToSet Insert a value into an array in the result document, but do not create a copy.
$first Gets the first document data according to the order of the resource documents.
$last Get the last document data by sorting the resource documents

Aggregation Pipeline

Pass the MongoDB document to the next pipeline after one pipeline has been processed.

$project: Modify the structure of the input document.It can be used to rename, add, or delete fields, as well as to create calculation results and nested documents.

$match: Used to filter data and output only qualified documents.$match uses MongoDB's standard query operation.

$limit: Used to limit the number of documents returned by the MongoDB aggregation pipeline.

$skip: skips a specified number of documents in the aggregation pipeline and returns the remaining documents.

$unwind: Split an array type field in the document into multiple strips, each containing one value in the array.

$group: Groups documents in a collection and can be used for statistical results.

$sort: Sorts input documents and outputs them.

$geoNear: Output an ordered document close to a geographic location.

$project instance

db.article.aggregate(
    { $project : {
        _id : 0 ,
        title : 1 ,
        author : 1
    }});

$match instance

db.articles.aggregate( [
                        { $match : { score : { $gt : 70, $lte : 90 } } },
                        { $group: { _id: null, count: { $sum: 1 } } }
                       ] );

$skip instance

db.article.aggregate(
    { $skip : 5 });

JAVA uses Mongodb

  1. Add jar package
<dependency>
   <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.4.2</version>
</dependency>

2. Connect to the database

 public static MongoDatabase getConnection(String dbName) {
        return new MongoClient("localhost", 27017).getDatabase(dbName);
    }

    public static MongoDatabase getConnection(String userName, String password, String dbName) {
        //Connecting to the MongoDB service can replace "localhost" as the IP address of the server if it is a remote connection
        //ServerAddress() has two parameters, server address and port
        ServerAddress serverAddress = new ServerAddress("localhost", 27017);
        List<ServerAddress> addrs = new ArrayList<ServerAddress>();
        addrs.add(serverAddress);

        //The three parameters of MongoCredential.createScramSha1Credential() are user name database name password
        MongoCredential credential = MongoCredential.createScramSha1Credential(userName, dbName, password.toCharArray());
        List<MongoCredential> credentials = new ArrayList<MongoCredential>();
        credentials.add(credential);

        //Get a MongoDB connection through connection authentication
        MongoClient mongoClient = new MongoClient(addrs, credentials);

        return mongoClient.getDatabase(dbName);
    }

3. Insert Document

    @Test
    public void testInsertDocument() throws Exception {
        MongoCollection<Document> collection = MongoDBUtils.getConnection("hqq").getCollection("table2");

        Document doc1 = new Document("x", 1);
        Document doc2 = new Document("y", 2);
        Document doc3 = new Document("z", 3);
        List<Document> documents = Arrays.asList(doc2, doc3);

        collection.insertOne(doc1);
        collection.insertMany(documents);
    }

4. Query Documents

    @Test
    public void testFindDocument() throws Exception {
        MongoCollection<Document> collection = MongoDBUtils.getConnection("hqq").getCollection("table2");
        MongoCursor<Document> iterator = collection.find().iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

5. Update Documents

    @Test
    public void testUpdateDocument() throws Exception {
        MongoCollection<Document> collection = MongoDBUtils.getConnection("hqq").getCollection("table2");
        collection.updateOne(Filters.eq("x", 1), new Document("$set", new Document("x", 100)));
        collection.updateMany(Filters.eq("x", 1), new Document("$set", new Document("x", 100)));
    }

6. Delete Documents

    @Test
    public void testDeleteDocument() throws Exception {
        MongoCollection<Document> collection = MongoDBUtils.getConnection("hqq").getCollection("table2");
        collection.deleteOne(Filters.eq("x", 100));
        collection.deleteMany(Filters.eq("x", 100));
    }

Topics: MongoDB Database SQL JSON