1. 程式人生 > >MongoDB 內嵌文件查詢

MongoDB 內嵌文件查詢

java查詢程式碼

/**
 * 查詢教師年齡 30 歲 且所帶 年齡為 20 歲且來自 china 學生的教師
 */
@Test
public void  queryTest(){
    BasicDBList basicDBList=new BasicDBList();
//教師姓名
basicDBList.add(new BasicDBObject("age","30"));
//內嵌文件多條件
basicDBList.add(new BasicDBObject("studentList", new BasicDBObject("$elemMatch",new BasicDBObject("from"
,"china")))); basicDBList.add(new BasicDBObject("studentList", new BasicDBObject("$elemMatch",new BasicDBObject("age","20")))); DBObject obj =new BasicDBObject(); // and 查詢 obj.put("$and", basicDBList); Query query= new BasicQuery(obj); List<Teacher> teachers = mongoTemplate.find(query, Teacher.class
); }

教師資訊(get 、set 省略)

/**
 * @author Cheng.Wei
 * @ClassName Teacher
 * @Description 教師資訊
 * @date 2017-09-26 16:23
 */
@Document(collection = "student")
public class Teacher implements Serializable{
    @Id
private String id;
    private String name;
    private Integer age;
    private List<Student> studentList
; }

學生資訊(get 、set 省略)

/**
 * @author Cheng.Wei
 * @ClassName Student
 * @Description 學生資訊
 * @date 2017-09-26 16:14
 */
public class Student {
    private String name;
    private Integer age;
    private String from;

}