mongodb表关联

发布时间 2023-11-15 17:53:11作者: slnngk

 

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" } ] }