MongoDB 常用操作总结

本贴最后更新于 2616 天前,其中的信息可能已经沧海桑田

一、插入(insert)

添加单个数据:

db.inventory.insertOne( { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } } )

添加多个数据:

db.inventory.insertMany([ { item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } }, { item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } }, { item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } } ]) 对应的java操作方式: Document canvas = new Document("item", "canvas") .append("qty", 100) .append("tags", singletonList("cotton")); Document size = new Document("h", 28) .append("w", 35.5) .append("uom", "cm"); canvas.put("size", size); collection.insertOne(canvas); collection.insertMany(asList( Document.parse("{ item: 'journal', qty: 25, size: { h: 14, w: 21, uom: 'cm' }, status: 'A' }"), Document.parse("{ item: 'notebook', qty: 50, size: { h: 8.5, w: 11, uom: 'in' }, status: 'A' }"), Document.parse("{ item: 'paper', qty: 100, size: { h: 8.5, w: 11, uom: 'in' }, status: 'D' }"), Document.parse("{ item: 'planner', qty: 75, size: { h: 22.85, w: 30, uom: 'cm' }, status: 'D' }"), Document.parse("{ item: 'postcard', qty: 45, size: { h: 10, w: 15.25, uom: 'cm' }, status: 'A' }") ));

二、查询(Query)

查询所有:

db.inventory.find( {} ) 对应的sql类似于: SELECT * FROM inventory 对应的java查询方式: FindIterable<Document> findIterable = collection.find(new Document());

=号查询:

{ <field1>: <value1>, ... } db.inventory.find( { status: "D" } ) 对应的sql类似于: SELECT * FROM inventory WHERE status = "D"; 对应的java查询方式: and(eq( <field1>, <value1>), eq( <field2>, <value2>) ...) findIterable = collection.find(eq("status", "D"));

使用查询操作符:

{ <field1>: { <operator1>: <value1> }, ... } db.inventory.find( { status: { $in: [ "A", "D" ] } } ) 对应的sql类似于: SELECT * FROM inventory WHERE status in ("A", "D") 对应的java查询方式: and(gte(<field1>, <value1>), lt(<field2>, <value2>), eq(<field3>, <value3>)) findIterable = collection.find(in("status", "A", "D"));

AND 操作:

db.inventory.find( { status: "A", qty: { $lt: 30 } } ) 对应的sql类似于: SELECT * FROM inventory WHERE status = "A" AND qty < 30; 对应的java查询方式: findIterable = collection.find(and(eq("status", "A"), lt("qty", 30)));

OR 操作:

db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } ) 对应的sql类似于: SELECT * FROM inventory WHERE status = "A" OR qty < 30; 对应的java查询方式: findIterable = collection.find(or(eq("status", "A"), lt("qty", 30)));

AND 和 OR 同时使用:

db.inventory.find( { status: "A", $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ] } ) 对应的sql类似于: SELECT * FROM inventory WHERE status = "A" AND (qty < 30 OR item like "p%"); 对应的java查询方式: findIterable = collection.find( and(eq("status", "A"), or(lt("qty", 30), regex("item", "^p"))) );

嵌套查询:

db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } ) 对应的java查询方式: FindIterable<Document> findIterable = collection.find(eq("size", Document.parse("{ h: 14, w: 21, uom: 'cm' }"))); 使用{ <field>: <value> }进行嵌套查询: db.inventory.find( { "size.uom": "in" } ) 对应的java查询方式: findIterable = collection.find(eq("size.uom", "in")); 使用{ <field1>: { <operator1>: <value1> }, ... }进行嵌套查询: db.inventory.find( { "size.h": { $lt: 15 } } ) 对应的java查询方式: findIterable = collection.find(lt("size.h", 15));

匹配数组:

确切匹配“red”和“blank”元素,包括元素顺序:

db.inventory.find( { tags: ["red", "blank"] } ) 对应的java查询方式: FindIterable<Document> findIterable = collection.find(eq("tags", asList("red", "blank")));

只要包含“red”和“blank”元素,忽略其他元素和顺序:

db.inventory.find( { tags: { $all: ["red", "blank"] } } ) 对应的java查询方式: findIterable = collection.find(all("tags", asList("red", "blank")));

数组至少包含一个指定元素:

db.inventory.find( { tags: "red" } ) 对应的java查询方式: findIterable = collection.find(eq("tags", "red"));

使用操作符:(如匹配在 dim_cm 数组属性中至少有一个元素大于 25)

db.inventory.find( { dim_cm: { $gt: 25 } } ) 对应的java查询方式: findIterable = collection.find(gt("dim_cm", 25));

至少一个元素同时满足多个条件:

db.inventory.find( { dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } } ) 对应的java查询方式: findIterable = collection.find(elemMatch("dim_cm", Document.parse("{ $gt: 22, $lt: 30 }")));

根据数组指定某个元素取:(如取第二个元素)

db.inventory.find( { "dim_cm.1": { $gt: 25 } } ) 对应的java查询方式: findIterable = collection.find(gt("dim_cm.1", 25));

根据数组的 size 取:

db.inventory.find( { "tags": { $size: 3 } } ) 对应的java查询方式: findIterable = collection.find(size("tags", 3));

数组中包含内嵌元素的:(如下查询某元素完整匹配该内嵌元素,包括属性顺序)

db.inventory.find( { "instock": { warehouse: "A", qty: 5 } } ) 对应的java查询方式: FindIterable<Document> findIterable = collection.find(eq("instock", Document.parse("{ warehouse: 'A', qty: 5 }")));

指定数组内嵌元素,根据其某个属性做查询操作:

db.inventory.find( { 'instock.0.qty': { $lte: 20 } } ) 对应的java查询方式: findIterable = collection.find(lte("instock.0.qty", 20));

匹配所有数组内嵌元素,只要有内嵌元素该属性符合情况,则查询出来:

db.inventory.find( { 'instock.qty': { $lte: 20 } } ) 对应的java查询方式: findIterable = collection.find(lte("instock.qty", 20));

单个内嵌元素指定属性同时符合两条件:($elemMatch 操作符,表示单个属性同时满足)

db.inventory.find( { "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } } ) 对应的java查询方式: indIterable = collection.find(elemMatch("instock", Document.parse("{ qty: { $gt: 10, $lte: 20 } }")));

表示只要有属性满足大于 10,有属性满足小于 20,即被取出。

db.inventory.find( { 'instock.qty': { $lte: 20 , $gt: 10} } )

取集合中元素的指定属性:

db.inventory.find( { status: "A" }, { item: 1, status: 1 } ) 对应的java查询方式: findIterable = collection.find(eq("status", "A")).projection(include("item", "status")); 对应的sql类似于: SELECT _id, item, status from inventory WHERE status = "A" db.inventory.find( { status: "A" }, { item: 1, status: 1, "size.uom": 1 } ) 对应的java查询方式: findIterable = collection.find(eq("status", "A")).projection(include("item", "status", "size.uom"));

不取_id

db.inventory.find( { status: "A" }, { item: 1, status: 1, _id: 0 } ) 对应的sql类似于: SELECT item, status from inventory WHERE status = "A" 对应的java查询方式: findIterable = collection.find(eq("status", "A")) .projection(fields(include("item", "status"), excludeId()));

取除了 xx 的所有字段:

db.inventory.find( { status: "A" }, { status: 0, instock: 0 } ) 对应的sql类似于: findIterable = collection.find(eq("status", "A")).projection(exclude("item", "status")); db.inventory.find( { status: "A" }, { "size.uom": 0 } ) 对应的java查询方式: findIterable = collection.find(eq("status", "A")).projection(exclude("size.uom"));

根据 null 来查询:(查询该属性为 null 或不含该属性的信息)

db.inventory.find( { item: null } ) 对应的java查询方式: FindIterable<Document> findIterable = collection.find(eq("item", null));

查询属性值为 null 的信息:

db.inventory.find( { item : { $type: 10 } } ) 对应的java查询方式: findIterable = collection.find(type("item", BsonType.NULL));

查询不存在该属性的信息:

db.inventory.find( { item : { $exists: false } } ) 对应的java查询方式: findIterable = collection.find(exists("item", false));

三、更新(Update)

更新多个属性:

{ <update operator>: { <field1>: <value1>, ... }, <update operator>: { <field2>: <value2>, ... }, ... } combine(set( <field1>, <value1>), set(<field2>, <value2> ) )

根据条件更新单个文档:

db.inventory.updateOne( { item: "paper" }, { $set: { "size.uom": "cm", status: "P" }, $currentDate: { lastModified: **true** } } ) 对应的java操作方式: collection.updateOne(eq("item", "paper"), combine(set("size.uom", "cm"), set("status", "P"), currentDate("lastModified")));

根据条件更新多个文档:

db.inventory.updateMany( { "qty": { $lt: 50 } }, { $set: { "size.uom": "in", status: "P" }, $currentDate: { lastModified: **true** } } ) 对应的java操作方式: collection.updateMany(lt("qty", 50), combine(set("size.uom", "in"), set("status", "P"), currentDate("lastModified")));

根据条件替换单个文档

db.inventory.replaceOne( { item: "paper" }, { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] } ) 对应的java操作方式: collection.replaceOne(eq("item", "paper"), Document.parse("{ item: 'paper', instock: [ { warehouse: 'A', qty: 60 }, { warehouse: 'B', qty: 40 } ] }"));

四、删除(Delete)

删除全部:

db.inventory.deleteMany({}) 对应的java操作方式: collection.deleteMany(new Document());

删除符合条件的所有文档:

{ <field1>: <value1>, ... } 对应的java操作方式: and(eq( <field1>, <value1>), eq( <field2>, <value2>) ...) { <field1>: { <operator1>: <value1> }, ... } 对应的java操作方式: and(gte(<field1>, <value1>), lt(<field2>, <value2>), eq(<field3>, <value3>)) db.inventory.deleteMany({ status : "A" }) 对应的java操作方式: collection.deleteMany(eq("status", "A"));

删除符合条件的第一个文档:

db.inventory.deleteOne( { status: "D" } ) 对应的java操作方式: collection.deleteOne(eq("status", "D"));

五、聚合

aggregate:

db.orders.aggregate([ { $match: { status : “A” } }, { $group: { _id: “$cust_id”, total: { $sum: “$amount” } } } ])

聚合逻辑如下图所示:
7d5e8a78c0834eb18968ab920ef2babd-image.png

distinct:

db.orders.distinct( “cust_id” )

六、全文搜索

为需要进行全文搜索的属性设立索引:

db.stores.createIndex( { name: "text", description: "text" } )

使用 $ text 查询操作符在一个带有文本索引的集合上执行文本搜索:(查询 java,coffee 或 shop)

db.stores.find( { $text: { $search: "java coffee shop" } } )

精确的短语查询:(查询 java 或 coffee shop)

db.stores.find( { $text: { $search: "java \"coffee shop\"" } } )

排除:(查询 java 或 shop,但不含 coffee)

db.stores.find( { $text: { $search: "java shop -coffee" } } )

根据文本匹配度排序:

db.stores.find( { $text: { $search: "java coffee shop" } }, { score: { $meta: "textScore" } } ).sort( { score: { $meta: "textScore" } } )

参考自菜鸟教程:http://www.runoob.com/mongodb/mongodb-tutorial.html

  • MongoDB

    MongoDB(来自于英文单词“Humongous”,中文含义为“庞大”)是一个基于分布式文件存储的数据库,由 C++ 语言编写。旨在为应用提供可扩展的高性能数据存储解决方案。MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。它支持的数据结构非常松散,是类似 JSON 的 BSON 格式,因此可以存储比较复杂的数据类型。

    90 引用 • 59 回帖 • 7 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...