mongo database query spring query

Query, whether it is relational database or mongodb such nosql, is used more, most of the operations are read operations.
There are many ways to query mongodb, but only some common ones are listed below, such as:
1.= query
2. Fuzzy query
3. Greater than less than range query
4.in query
5.or query
6. Query one, query all
7. Learn by yourself

Query all qualified data according to the author, and return list < article >

Query query = Query.query(Criteria.where("author").is("yinjihuan"));
List<Article> articles = mongoTemplate.find(query, Article.class);

Only the first qualified data is queried, and the Article object is returned

query = Query.query(Criteria.where("author").is("yinjihuan"));
Article article = mongoTemplate.findOne(query, Article.class);

Query all data in the collection without conditions

articles = mongoTemplate.findAll(Article.class);

Query qualified quantity

query = Query.query(Criteria.where("author").is("yinjihuan"));
long count = mongoTemplate.count(query, Article.class);

Query by primary key ID

article = mongoTemplate.findById(new ObjectId("57c6e1601e4735b2c306cdb7"), Article.class);

in query

List<String> authors = Arrays.asList("yinjihuan", "jason");
query = Query.query(Criteria.where("author").in(authors));
articles = mongoTemplate.find(query, Article.class);

ne (! =) query

query = Query.query(Criteria.where("author").ne("yinjihuan"));
articles = mongoTemplate.find(query, Article.class);

LT (< query articles with less than 10 visits

query = Query.query(Criteria.where("visitCount").lt(10));
articles = mongoTemplate.find(query, Article.class);

Range query, greater than 5 but less than 10

query = Query.query(Criteria.where("visitCount").gt(5).lt(10));
articles = mongoTemplate.find(query, Article.class);

Fuzzy query, data of a in author

query = Query.query(Criteria.where("author").regex("a"));
articles = mongoTemplate.find(query, Article.class);

Array query, query the data of 3 in tags

query = Query.query(Criteria.where("tags").size(3));
articles = mongoTemplate.find(query, Article.class);

Or query, query the data of author=jason or visitCount=0

query = Query.query(Criteria.where("").orOperator(
    Criteria.where("author").is("jason"),
    Criteria.where("visitCount").is(0)));
articles = mongoTemplate.find(query, Article.class);


Author: Yin Jihuan
Link: https://www.jianshu.com/p/502dbdb7613e
Source: Jianshu

Tags: less MongoDB Database

Posted on Thu, 13 Feb 2020 14:14:00 -0500 by CybJunior