顯示具有 [ MangoDB ] 標籤的文章。 顯示所有文章
顯示具有 [ MangoDB ] 標籤的文章。 顯示所有文章

2015年12月21日 星期一

[ MongoDB 文件 ] Getting Started - Data Aggregation with Java Driver

Source From Here 
Overview 
MongoDB can perform aggregation operations, such as grouping by a specified key and evaluating a total or a count for each distinct group. Use the aggregate method to perform a stage-based aggregation. The aggregate method accepts as its argument an array of stages, where each stage, processed sequentially, describes a data processing step. 

Prerequisites 
The examples in this section use the restaurants collection in the test database. For instructions on populating the collection with the sample dataset, see Import Example Dataset. Follow the Connect to MongoDB step to connect to a running MongoDB instance and declare and define the variable db to access the test database. To begin, including the following import statements. 
  1. import com.mongodb.Block;  
  2. import com.mongodb.client.AggregateIterable;  
  3. import org.bson.Document;  
  4.   
  5. import static java.util.Arrays.asList;  
Group Documents by a Field and Calculate Count 
Use the $group stage to group by a specified key. In the $group stage, specify the group by key in the _id field. $group accesses fields by the field path, which is the field name prefixed by a dollar sign $. The $group stage can useaccumulators to perform calculations for each group. The following example groups the documents in the restaurants collection by the borough field and uses the $sum accumulator to count the documents for each group. 
  1. AggregateIterable iterable = db.getCollection("restaurants").aggregate(asList(  
  2.         new Document("$group"new Document("_id""$borough").append("count"new Document("$sum"1)))));  
  3.   
  4. iterable.forEach(new Block() {  
  5.     @Override  
  6.     public void apply(final Document document) {  
  7.         System.out.println(document.toJson());  
  8.     }  
  9. });  
The result set consists of the following documents: 
{ "_id" : "Missing", "count" : 51 }
{ "_id" : "Staten Island", "count" : 969 }
{ "_id" : "Manhattan", "count" : 10259 }
{ "_id" : "Brooklyn", "count" : 6086 }
{ "_id" : "Queens", "count" : 5656 }
{ "_id" : "Bronx", "count" : 2338 }

The _id field contains the distinct borough value, i.e., the group by key value. 

Filter and Group Documents 
Use the $match stage to filter documents. $match uses the MongoDB query syntax. The following pipeline uses $match to query the restaurants collection for documents with borough equal to "Queens" and cuisine equal to Brazilian. Then the $group stage groups the matching documents by the address.zipcode field and uses the $sum accumulator to calculate the count. $group accesses fields by the field path, which is the field name prefixed by a dollar sign $
  1. AggregateIterable iterable = db.getCollection("restaurants").aggregate(asList(  
  2.         new Document("$match"new Document("borough""Queens").append("cuisine""Brazilian")),  
  3.         new Document("$group"new Document("_id""$address.zipcode").append("count"new Document("$sum"1)))));  
  4.   
  5. iterable.forEach(new Block() {  
  6.     @Override  
  7.     public void apply(final Document document) {  
  8.         System.out.println(document.toJson());  
  9.     }  
  10. });  
The result set consists of the following documents: 
{ "_id" : "11377", "count" : 1 }
{ "_id" : "11368", "count" : 1 }
{ "_id" : "11101", "count" : 2 }
{ "_id" : "11106", "count" : 3 }
{ "_id" : "11103", "count" : 1 }

The _id field contains the distinct zipcode value, i.e., the group by key value. 

Additional Information 
In the Java Driver documentation, see aggregateAggregateIterableBlock; In the MongoDB Manual, see also Aggregation Quick Reference, the SQL to Aggregation Mapping Chart, and Aggregation Introduction

Supplement 
Getting Started - Remove Data with Java Driver 
Getting Started - Indexes with Java Driver

2015年12月8日 星期二

[ MongoDB 文件 ] Getting Started - Remove Data with Java Driver

Source From Here 
Overview 
You can use the deleteOne method and the deleteMany method to remove documents from a collection. The method takes a conditions document that determines the documents to remove. To specify a remove condition, use the same structure and syntax as the query conditions. See Find or Query Data with Java Driver for an introduction to query conditions. 

Prerequisites 
The examples in this section use the restaurants collection in the test database. For instructions on populating the collection with the sample dataset, see Import Example Dataset. Follow the Connect to MongoDB step to connect to a running MongoDB instance and declare and define the variable db to access the test database. To begin, including the following import statements. 
  1. import org.bson.Document;  
Procedures 

Remove All Documents That Match a Condition 
The following operation removes all documents that match the specified condition. 
  1. db.getCollection("restaurants").deleteMany(new Document("borough""Manhattan"));  
The deleteMany operation returns a DeleteResult which contains information about the operation. The getDeletedCount method returns number of documents deleted. 

Remove All Documents 
To remove all documents from a collection, pass an empty conditions document {} to the deleteMany method. 
  1. db.getCollection("restaurants").deleteMany(new Document());  
The deleteMany operation returns a DeleteResult which contains information about the operation. The getDeletedCount method returns number of documents deleted. 

Drop a Collection 
The remove all operation only removes the documents from the collection. The collection itself, as well as any indexes for the collection, remain. To remove all documents from a collection, it may be more efficient to drop the entire collection, including the indexes, and then recreate the collection and rebuild the indexes. Use the drop method to drop a collection, including any indexes. 
  1. db.getCollection("restaurants").drop();  
Additional Information 
In the Java Driver documentation, see deleteOnedeleteMany and drop; In MongoDB, write operations are atomic on the level of a single document. If a single remove operation removes multiple documents from a collection, the operation can interleave with other write operations on that collection. In the MongoDB Manual, see Atomicity

Supplement 
Getting Started - Update Data with Java Driver 
Getting Started - Data Aggregation with Java Driver

[ MongoDB 文件 ] Getting Started - Update Data with Java Driver

Source From Here 
Overview 
You can use the updateOne method, updateMany method, and replaceOne method to update documents of a collection. The methods accept the following parameters: 
* a filter document to match the documents to update,
* an update document to specify the modification to perform, and
* an options parameter (optional).

To specify the filter, use the same structure and syntax as the query conditions. See Find or Query Data with Java Driver for an introduction to query conditions. However, you cannot update the _id field. 

Prerequisites 
The examples in this section use the restaurants collection in the test database. For instructions on populating the collection with the sample dataset, see Import Example Dataset. Follow the Connect to MongoDB step to connect to a running MongoDB instance and declare and define the variable db to access the test database. To begin, including the following import statements. 
  1. import org.bson.Document;  
  2. import static java.util.Arrays.asList;  
Update Specific Fields 
To change a field value, MongoDB provides update operators, such as $set to modify values. Some update operators, such as $set, will create the field if the field does not exist. See the individual update operators reference

Update Top-Level Fields 
The following operation updates the first document with name equal to "Juni", using the $set operator to update the cuisine field and the $currentDate operator to update the lastModified field with the current date. 
  1. db.getCollection("restaurants").updateOne(new Document("name""Juni"),  
  2.         new Document("$set"new Document("cuisine""American (New)"))  
  3.             .append("$currentDate"new Document("lastModified"true)));  
The updateOne operation returns a UpdateResult which contains information about the operation. The getModifiedCount method returns the number of documents modified. 

Update an Embedded Field 
To update a field within an embedded document, use the dot notation. When using the dot notation, enclose the whole dotted field name in quotes. The following updates the street field in the embedded address document. 
  1. db.getCollection("restaurants").updateOne(new Document("restaurant_id""41156888"),  
  2.         new Document("$set"new Document("address.street""East 31st Street")));  
Update Multiple Documents 
To update multiple documents, use the updateMany method. The following operation updates all documents that have address.zipcode field equal to "10016" and cuisine field equal to "Other", setting the cuisine field to "Category To Be Determined" and the lastModified field to the current date. 
  1. db.getCollection("restaurants").updateMany(new Document("address.zipcode""10016").append("cuisine""Other"),  
  2.         new Document("$set"new Document("cuisine""Category To Be Determined"))  
  3.                 .append("$currentDate"new Document("lastModified"true)));  
The updateMany operation returns a UpdateResult which contains information about the operation. The getModifiedCount method returns the number of documents modified. 

Replace a Document 
To replace the entire document except for the _id field, pass an entirely new document as the second argument to the replaceOne method. The replacement document can have different fields from the original document. In the replacement document, you can omit the _id field since the _id field is immutable. If you do include the _id field, it must be the same value as the existing value. 
Important. 
After the update, the document only contains the field or fields in the replacement document.

After the following update, the modified document will only contain the _id field, name field, the address field. i.e. the document will not contain the restaurant_idcuisinegrades, and the borough fields. 
  1. db.getCollection("restaurants").replaceOne(new Document("restaurant_id""41704620"),  
  2.         new Document("address",  
  3.                 new Document()  
  4.                         .append("street""2 Avenue")  
  5.                         .append("zipcode""10075")  
  6.                         .append("building""1480")  
  7.                         .append("coord", asList(-73.955741340.7720266)))  
  8.                 .append("name""Vella 2"));  
The replaceOne operation returns a UpdateResult which contains information about the operation. The getModifiedCount method returns the number of documents modified. 

Additional Information 
If no document matches the update condition, the default behavior of the update method is to do nothing. By specifying the upsert option to true, the update operation either updates matching document(s) or inserts a new document if no matching document exists. In the Java Driver documentation, see updateOneupdateMany, and replaceOne as well as updateOptions

In MongoDB, write operations are atomic on the level of a single document. If a single update operation modifies multiple documents of a collection, the operation can interleave with other write operations on that collection. In the MongoDB Manual, see Atomicity. For all available update operators, see the Update Operators reference page in the MongoDB Manual. 

Supplement 
Getting Started - Find and Query Data with Java Driver 
Getting Started - Remove Data with Java Driver

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...