mongodb表关联

 

books表

db.books.insert(
  {_id:123, book_name:"Head First Java", 
  author:"Kathy Sierra", 
  publisher:"O'Reilly"}
);

 

publishers表

db.publishers.insert(
  {_id:123, publisherName:"O'Reilly", 
  location:"San Francisco"}
);

 

关联查询:

复制代码
db.books.aggregate([ 
    {
        $lookup: 
        {
            from: "publishers", ##从哪个表查询
            localField: "publisher",      ##
            foreignField:"publisherName", 
            as:"publisher_data"
        }
    }
]);
复制代码

 

复制代码
mongos> db.books.aggregate([ 
...     {
...         $lookup: 
...         {
...             from: "publishers",
...             localField: "publisher",
...             foreignField:"publisherName", 
...             as:"publisher_data"
...         }
...     }
... ]);
{ "_id" : 123, "book_name" : "Head First Java", "author" : "Kathy Sierra", "publisher" : "O'Reilly", "publisher_data" : [ { "_id" : 123, "publisherName" : "O'Reilly", "location" : "San Francisco" } ] }
复制代码

 

使用说明:

复制代码
{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}
复制代码

 

posted @   slnngk  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2022-11-15 安装部署etcd
点击右上角即可分享
微信分享提示