使用Java操作MongoDB - Query

Query

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
Mongo mg = new Mongo("localhost", 27017);
// get db
db = mg.getDB("CRUD");
// get collection
dc = db.getCollection("test");

// findOne
System.out.println(dc.findOne());

// find all
DBCursor cursor = dc.find();
while(cursor.hasNext()){
System.out.println(cursor.next());
}

// display certain column
BasicDBObject keys = new BasicDBObject();
keys.put("name", 1);
keys.put("_id", 0);
DBCursor cursor = dc.find(new BasicDBObject(), keys);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}

// equal | greater | less | not equal | regex
BasicDBObject query = new BasicDBObject();
//query.put("name", "hulu1");
//query.put("number", new BasicDBObject("$gt", 2));
//query.put("number", new BasicDBObject("$gte", 2));
//query.put("number", new BasicDBObject("$lt", 5));
//query.put("number", new BasicDBObject("$lte", 5));
//query.put("name", new BasicDBObject("$ne", "hulu1"));
query.put("name", new BasicDBObject("$regex", "hulu.*"));
DBCursor cursor = dc.find(query);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}

// in | not in
BasicDBObject query = new BasicDBObject();
List<String> list = new ArrayList<String>();
list.add("hulu1");
list.add("hulu4");
query.put("name", new BasicDBObject("$nin", list));
DBCursor cursor = dc.find(query);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}

// and
BasicDBObject query = new BasicDBObject();
query.put("number", new BasicDBObject("$gt", 2));
query.put("name", "hulu1");
DBCursor cursor = dc.find(query);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}

// or
BasicDBObject query = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("name", "hulu1"));
obj.add(new BasicDBObject("number", new BasicDBObject("$gt", 2)));
query.put("$or", obj);
DBCursor cursor = dc.find(query);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}

唐胡璐 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
分享创造价值,您的支持将鼓励我继续前行!