第一步引入包:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.8.2</version>
</dependency>
第二步 注入MongoClient到Spring中
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
@Configuration
public class MongoDataSource {
@Value("${mongodb.uri}")
private String mongoDBUri;
@Bean
public MongoClient init() {
MongoClientURI mouri= new MongoClientURI(this.mongoDBUri);
MongoClient clinet = new MongoClient(mouri);
return clinet;
}
}
第三步,调用
//必须引入要不然eq会报错
import static com.mongodb.client.model.Filters.*;
@Autowired
MongoClient mongoClient;
public void test() {
MongoDatabase database = mongoClient.getDatabase("");
MongoCollection<Document> collection = database.getCollection("a");
collection.find(eq("name", "456 Cookies Shop"));
}
另外一种条件查询的方式
BasicDBObject query = new BasicDBObject();
//时间区间查询 记住如果想根据这种形式进行时间的区间查询 ,存储的时候 记得把字段存成字符串,就按yyyy-MM-dd HH:mm:ss 格式来
query.put("times", new BasicDBObject("$gte", "2018-06-02 12:20:00").append("$lte","2018-07-04 10:02:46"));
//模糊查询
Pattern pattern = Pattern.compile("^.*王.*$", Pattern.CASE_INSENSITIVE);
query.put("userName", pattern);
//精确查询
query.put("id", "11");
//skip 是分页查询,从第0条开始查10条数据。 Sorts是排序用的。有descending 和ascending
MongoCursor<Document> cursor = collection.find(query).sort(Sorts.orderBy(Sorts.descending("times"))).skip(0).limit(10).iterator();//
关联查询
import com.alibaba.fastjson.JSON;
import com.galaplat.product.center.databook.dao.BaseParam;
import com.galaplat.product.center.databook.dao.IMongoDao;
import com.galaplat.product.center.databook.dao.OperateParam;
import com.galaplat.product.center.databook.dao.mongo.BaseDO;
import com.galaplat.product.center.databook.enums.OperateTypeEnums;
import com.google.common.collect.Lists;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.*;
import com.mongodb.client.model.Accumulators;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.IndexModel;
import com.mongodb.client.model.Projections;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.bson.BsonDocument;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.Decimal128;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Transient;
import org.springframework.stereotype.Repository;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
/**
* 通用操作mongodb的DAO层实现类
*
* @author yanjing
* @date 2019年9月2日 下午3:31:39
*/
@Repository
public class MongoDaoImpl implements IMongoDao {
@Autowired
private MongoClient mongoClient;
@