sql >> データベース >  >> NoSQL >> MongoDB

Javaを使用したMongo3.2ドライバーによる新しい集約機能

    次の集計パイプラインを実行すると、必要な結果が得られます

    pipeline = [
        {
            "$match": {
                "_id": employeeId
            }
        },
        {
            "$lookup": {
                "from": "company", 
                "localField": "companyId",
                "foreignField": "_id",
                "as": "company"
            }
        },
        {
            "$project": {
                "name": 1,
                "lastName": 1,
                "companyId": 1,
                "companyName": "$company.companyName"
            }
        }
    ];
    db.employee.aggregate(pipeline);
    

    Javaテストの実装

    public class JavaAggregation {
        public static void main(String args[]) throws UnknownHostException {
    
            MongoClient mongo = new MongoClient();
            DB db = mongo.getDB("test");
    
            DBCollection coll = db.getCollection("employee");
    
            // create the pipeline operations, first with the $match
            DBObject match = new BasicDBObject("$match",
                new BasicDBObject("_id", employeeId)
            );
    
            // build the $lookup operations
            DBObject lookupFields = new BasicDBObject("from", "company");
            lookupFields.put("localField", "companyId");
            lookupFields.put("foreignField", "_id");
            lookupFields.put("as", "company");      
            DBObject lookup = new BasicDBObject("$lookup", lookupFields);
    
            // build the $project operations
            DBObject projectFields = new BasicDBObject("name", 1);
            projectFields.put("lastName", 1);
            projectFields.put("companyId", 1);
            projectFields.put("companyName", "$company.companyName");       
            DBObject project = new BasicDBObject("$project", projectFields);
    
            List<DBObject> pipeline = Arrays.asList(match, lookup, project);
    
            AggregationOutput output = coll.aggregate(pipeline);
    
            for (DBObject result : output.results()) {
                System.out.println(result);
            }
        }
    }
    



    1. MongoDB $ filter

    2. mongodbに.bsonファイル形式をインポートする方法

    3. Node.js-マングースとの関係の作成

    4. MongoDBの'count()'は非常に遅いです。どのようにそれを改良/回避しますか?