Hướng dẫn lookup trong mongodb
Yêu cầu thg 7 31, 2018 7:31 SA• 4215 0 0 Show Chào mọi người. Mình có 1 app đang làm sử dụng mongodb. Do mới tiếp xúc nên có vấn đề mình gặp phải cần mọi người trợ giúp. Mình có 3 model liên quan cụ thể các field phía dưới. Từ Model Review, mình muốn lấy toàn bộ reviews của Book. router api dạng: domain/book_id/reviews. Mỗi review sẽ có comments nên get luôn các comment của review tương ứng( và info tác giả của comment đó). Trong từng comment có trường user_id. Ở đây mình dùng các table riêng biệt. Lúc trước minh dùng foEarch lấy ra từng ID rồi truy vấn để lấy thông tin. Nhưng thấy nó Load mất thời gian. Sau đó thì tìm hiểu đc cái lookup và populate này. Mình dùng câu truy vấn như này ở Model review.
Kết quả sẽ ra được như thế này. Mình muốn là ở cái user_id sẽ hiển thị Object thông tin User đó luôn. Kiểu như bình thường sử dụng populate thì sẽ là Comment.user_id ấy.
Thông tin các Model Review
Comment Docs Home → MongoDB Manual On this page
$lookup Changed in version 5.1. Performs a left outer join to a collection in the same database to filter in documents from the "joined" collection for processing. The
Starting in MongoDB 5.1, To combine elements from two different collections, use the The To perform an equality match between a field from the input documents with a field from the documents of the "joined" collection, the
The
The operation would correspond to the following pseudo-SQL statement:
See these examples:
MongoDB 3.6 adds support for:
In MongoDB, a correlated subquery is a pipeline in a NoteStarting in MongoDB 5.0, for an uncorrelated subquery in a MongoDB correlated subqueries are comparable to SQL correlated subqueries, where the inner query references outer query values. An SQL uncorrelated subquery does not reference outer query values. MongoDB 5.0 also supports concise correlated subqueries. To perform correlated and uncorrelated subqueries with two collections, and perform other join conditions besides a single equality match, use this
The
pipeline Specifies the The The NoteTo reference variables in pipeline stages, use the The
let variables can be accessed by the stages in the pipeline, including additional
as Specifies the name of the new array field to add to the joined documents. The new array field contains the matching documents from the joined collection. If the specified name already exists in the joined document, the existing field is overwritten. |