如何在MongoDB中執(zhí)行SQL Join等效項(xiàng)?如何在MongoDB中執(zhí)行SQL Join等效項(xiàng)?例如,假設(shè)你有兩個集合(用戶和評論),我想用pid = 444以及每個集合的用戶信息來提取所有評論。comments { uid:12345, pid:444, comment="blah" }
{ uid:12345, pid:888, comment="asdf" }
{ uid:99999, pid:444, comment="qwer" }users { uid:12345, name:"john" }
{ uid:99999, name:"mia" }有沒有辦法用一個字段拉出所有評論(例如......查找({pid:444}))以及與每個評論相關(guān)的用戶信息?目前,我首先得到符合我標(biāo)準(zhǔn)的注釋,然后找出該結(jié)果集中的所有uid,獲取用戶對象,并將它們與注釋的結(jié)果合并。好像我做錯了。
4 回答

手掌心
TA貢獻(xiàn)1942條經(jīng)驗(yàn) 獲得超3個贊
我們可以使用mongodb客戶端控制臺將只有一行的簡單函數(shù)合并/加入一個集合中的所有數(shù)據(jù),現(xiàn)在我們可以執(zhí)行所需的查詢。下面是一個完整的例子
.-作者:
db.authors.insert([ { _id: 'a1', name: { first: 'orlando', last: 'becerra' }, age: 27 }, { _id: 'a2', name: { first: 'mayra', last: 'sanchez' }, age: 21 }]);
.-分類:
db.categories.insert([ { _id: 'c1', name: 'sci-fi' }, { _id: 'c2', name: 'romance' }]);
.-書籍
db.books.insert([ { _id: 'b1', name: 'Groovy Book', category: 'c1', authors: ['a1'] }, { _id: 'b2', name: 'Java Book', category: 'c2', authors: ['a1','a2'] },]);
.-圖書借閱
db.lendings.insert([ { _id: 'l1', book: 'b1', date: new Date('01/01/11'), lendingBy: 'jose' }, { _id: 'l2', book: 'b1', date: new Date('02/02/12'), lendingBy: 'maria' }]);
。- 魔法:
db.books.find().forEach( function (newBook) { newBook.category = db.categories.findOne( { "_id": newBook.category } ); newBook.lendings = db.lendings.find( { "book": newBook._id } ).toArray(); newBook.authors = db.authors.find( { "_id": { $in: newBook.authors } } ).toArray(); db.booksReloaded.insert(newBook); });
.-獲取新的收集數(shù)據(jù):
db.booksReloaded.find().pretty()
.-回應(yīng):)
{ "_id" : "b1", "name" : "Groovy Book", "category" : { "_id" : "c1", "name" : "sci-fi" }, "authors" : [ { "_id" : "a1", "name" : { "first" : "orlando", "last" : "becerra" }, "age" : 27 } ], "lendings" : [ { "_id" : "l1", "book" : "b1", "date" : ISODate("2011-01-01T00:00:00Z"), "lendingBy" : "jose" }, { "_id" : "l2", "book" : "b1", "date" : ISODate("2012-02-02T00:00:00Z"), "lendingBy" : "maria" } ]}{ "_id" : "b2", "name" : "Java Book", "category" : { "_id" : "c2", "name" : "romance" }, "authors" : [ { "_id" : "a1", "name" : { "first" : "orlando", "last" : "becerra" }, "age" : 27 }, { "_id" : "a2", "name" : { "first" : "mayra", "last" : "sanchez" }, "age" : 21 } ], "lendings" : [ ]}
我希望這條線可以幫到你。
- 4 回答
- 0 關(guān)注
- 1176 瀏覽
添加回答
舉報
0/150
提交
取消