MongoDB常用28条查询语句

SELECT SUM(score) from userInfo where createTime >= '2020-11-10 00:00:00' and createTime < '2020-11-11 00:00:00';

28、根据A表,匹配B表所有满足条件的集合,如根据用户表userInfo表中的userId字段找出userAdress表中所有地址的集合,其中userId也为userAdress中的字段。

假设 有 用户集合, 存储的测试数据 如下:

db.userInfo.insert([
   { "_id" : 1, "userId" : "xxxx", "username" : "ruink", "website" : "www.51ste.com" },
   { "_id" : 2, "userId" : "yyyy", "username" : "foosingy", "website" : "www.scgossip.com" }
])

假设 有 地址集合, 存储的测试数据 如下:

db.userAdress.insert([
   { "_id" : 1, "userId" : "xxxx", address: "测试地址1"},
   { "_id" : 2, "userId" : "yyyy", address: "测试地址2"},
   { "_id" : 3, "userId" : "xxxx", address: "测试地址3"},
])

查询语句:

db.userInfo.aggregate([
   {
     $lookup:
       {
         from: "userAdress",
         localField: "userId",
         foreignField: "userId",
         as: "address_detail"
       }
  },
  { $match : {"userId" :"xxxx"} }
])

上表为找出userId="xxxx"的所有地址的集合,查询结果如下:

[
  {
    _id: 1,
    userId: 'xxxx',
    username: 'ruink',
    website:'www.51ste.com',
    address_docs: [
      {
        _id: 1,
        userId: 'xxxx',
        address: '测试地址1'
      },
      {
        _id: 3,
        userId: 'xxxx',
        address: '测试地址3'
      }
    ]
  }
]

-- End --

文末寄语:  谁不向“前”看,谁就会面临许多困难。

上一页12下一页


留言