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 @ 2023-11-15 17:48  slnngk  阅读(29)  评论(0编辑  收藏  举报