MongoDB学习日记 - java代码(六):索引 index
来源:互联网 发布:ios app 访问数据库 编辑:程序博客网 时间:2024/06/05 08:31
这里的示例代码都是简要代码,详细代码可以参考我打包好的代码,地址:百度云 mongo-demo.rar
MongoDB 的索引太复杂了,这里就介绍下,基本够用;如果有开发需求,那么你还是仔细看看,功能还是很强大的,例如:地理位置索引等。
MongoClient client = new MongoClient();MongoDatabase database = client.getDatabase("mydb");MongoCollection<Document> collection = database.getCollection("test");// 语法解释 :db.test.createIndex({"i":1})collection.createIndex(new Document("i",1)); // 创建普通索引// 语法解释 :db.test.createIndex({"content":"text"})collection.createIndex(new Document("content","text")); // 创建文本索引ListIndexesIterable<Document> list = collection.listIndexes();for (Document document : list) { System.out.println(document.toJson());}client.close();
这里再讲讲文本索引的使用吧:
// 插入测试数据/*collection.insertOne(new Document("_id", 0).append("content", "textual content"));collection.insertOne(new Document("_id", 1).append("content", "additional content"));collection.insertOne(new Document("_id", 2).append("content", "irrelevant content"));*/long matchCount = collection.count(Filters.text("textual content -irrelevant"));System.out.println("Text search matches: " + matchCount);// Find using the $language operatorBson textSearch = Filters.text("textual irrelevant", "english");matchCount = collection.count(textSearch);System.out.println("Text search matches (english): " + matchCount);// Find the highest scoring matchDocument projection = new Document("score", new Document("$meta", "textScore"));Document myDoc = collection.find(textSearch).projection(projection).first();System.out.println("Highest scoring document: " + myDoc.toJson());
(注:这段代码是从 MongoDB 官网 copy 下的代码。)
- Filters.text() : 这是 MongoDB 的全文检索,通过文本索引来检索,语法解释如下(前面没讲):
db.runCommand("text", {search: "textual content -irrelevant"})
需要注意 "textual content -irrelevant"
这部分的意思是:通过创建的文本索引,查找所有包含 textual 和 content 而不包含 irrelevant 的 document(文档)。Filters.text("textual irrelevant", "english");
的意思则是匹配 english,可以添加多个 Filters.text("textual irrelevant", "english Chinese"
0 0
- MongoDB学习日记 - java代码(六):索引 index
- MongoDB学习日记(九):index
- MongoDB学习日记 - java代码(一):mongodb driver
- MongoDB学习日记(六):CRUD - update
- MongoDB学习日记 - java代码(二):建立连接
- MongoDB学习日记 - java代码(四):构建Document
- MongoDB学习日记 - java代码(五):增删改查
- MongoDB学习日记 - java代码(七):runCommand & BasicDBObject
- MongoDB学习日记 - java代码(三):数据库与集合操作
- MongoDb Architecture(index)-------MongoDb的体系结构(索引)
- 菜鸟的mongoDB学习---(六)MongoDB 索引
- MongoDB学习笔记(六) MongoDB索引用法和效率分析
- MongoDB学习笔记(六) MongoDB索引用法和效率分析
- MongoDB学习笔记(六) MongoDB索引用法和效率分析
- MongoDB学习笔记(六) MongoDB索引用法和效率分析
- MongoDB学习笔记(六) MongoDB索引用法和效率分析
- MongoDB学习笔记(六) MongoDB索引用法和效率分析
- MongoDB学习笔记(六) MongoDB索引用法和效率分析
- java.lang.InstantiationException
- Android Flowlayout实现的说明
- 数组的使用
- Android的垂直布局管理器的代码
- 程序算法艺术与实践:递归策略之递归,循环与迭代
- MongoDB学习日记 - java代码(六):索引 index
- ServletConfig和ServletContext的区别
- 自绘菜单
- 微软的免费开发工具
- java SE复习笔记5
- C++中的虚函数
- golang指针
- HDU 5213 Lucky [莫队+容斥]
- 将链表中的所有元素为奇数的节点移到元素为偶数节点的前面,并保证奇数之间顺序不变,偶数之间顺序不变(创新工场)