java整合mongodb--两表(聚合)

Test

import com.mongodb.*;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Field;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.junit.Before;
import org.junit.Test;

import java.util.*;


public class mongojava2 {

    MongoClient mongoClient=null;
    MongoCollection student=null;
    @Before
    public void before(){
        mongoClient = new MongoClient("/*host*/");
        MongoDatabase studentdb = mongoClient.getDatabase("student");//库
        student = studentdb.getCollection("student");//表
    }

    @Test
    public void findAll(){
        Bson lookup = Aggregates.lookup("grade", "gradeid", "_id", "grades");
        Map map = new HashMap();
        map.put("_id",1);
        map.put("name",1);
        map.put("age",1);
        map.put("sex",1);
        map.put("gradeName",1);
        BasicDBObject bson = new BasicDBObject(map);
        List list=new ArrayList();
        list.add(lookup);
        list.add( Aggregates.unwind("$grades"));
        list.add(Aggregates.addFields(new Field("gradeName","$grades.name")));
        list.add(Aggregates.project(bson));
        list.add(Aggregates.skip(1));//分页条件
        list.add(Aggregates.limit(2));//分页条件
        AggregateIterable aggregate = student.aggregate(list);
        for (Document document :aggregate
        ) {
            //System.out.println(document.toJson());
            System.out.println("编号:"+document.getInteger("_id"));
            System.out.println("姓名:"+document.getString("name"));
            System.out.println("年龄:"+document.getInteger("age"));
            System.out.println("性别:"+document.getString("sex"));
            System.out.println("班级:"+document.getString("gradeName"));
        }
    }

}

所需的包

        
            org.mongodb
            mongodb-driver
            3.8.2
        

你可能感兴趣的:(java整合mongodb--两表(聚合))