MongoDB数据库是不需要建表操作的

1、插入数据:

  •         db.集合名.insert({JSON类型})即可创建并且插入数据

2、多表查询:

  •         db.集合名.aggregate([对应的方法])即可实现多表查询

3、可能用到的函数:

  •         $set:{}设置值。
    •         $toString:将后面类型转化为字符串类型
      •         $lookUp:查询语句
        •         $match:where语句
          •         $skip:分页,第几页
            •         $limit:每页显示多少文字

接下来主要详解as属性值

-- 先建立表1
db.cus.insert([
{"_id": 1,"item": "almonds","price": 12,"quantity": 2}, 
{"_id": 2, "item": "pecans", "price": 20, "quantity": 1}
])
-- 再建立表二
db.inv.insert([
   { "_id" : 1, "sku" : "almonds", description: "product 1", "instock" : 120 },
   { "_id" : 2, "sku" : "bread", description: "product 2", "instock" : 80 },
   { "_id" : 3, "sku" : "cashews", description: "product 3", "instock" : 60 },
   { "_id" : 4, "sku" : "pecans", description: "product 4", "instock" : 70 },
	 { "_id" : 5, "sku" : "almonds", description: "product 5", "instock" : 300 }
])
--开始执行多表查询
db.cus.aggregate([  --表示cus为主表
   {
     $lookup: --将两张表链接起来,相当于join语句
       {
         from: "inv", --与哪个表链接
         localField: "item",--cus主表的item字段与另一个表sku去匹配匹配
         foreignField: "sku",-- inv副表的sku字段与主表item字段匹配才显示
         as: "inventory_docs" -- 查询出来的满足条件的结果名称
       }
  }
])

返回结果:首先会将主表的所有数据都返回,然后满足条件的存放于as起的别名中,最终返回一个集合类型,Java后台可用List<HashMap>接收,如果没有满足条件的就会返回null

最终的返回结果为:



展开inventory_docs对应的集合:


1、_id=1的返回结果为:


2、_id=2的返回结果为:

 

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐