Hướng dẫn lookup mongodb nodejs

The $lookup operator is an aggregation operator or an aggregation stage, which is used to join a document from one collection to a document of another collection of the same database based on some queries. Both the collections should belong to the same databases.

Aggregation in MongoDB is an operation that groups values from multiple documents together and can perform a variety of operations on the grouped data to return a single result. And $lookup is one of the operations which aggregation performs.

How $lookup works?

We have two collections, input collection [the collection on which $lookup is performed] and from collection [the collection from which we take documents to join it to documents of input collection].

$lookup takes selected documents from the “from collection” based on some queries and then attaches them to the document of “input collection” in a separate array field. It is just like a left outer join of SQL.

Perform $lookup with Equality Match:

In equality match, for each document, the value of any specific field of input collection document is compared with the value of any specific field of every from collection documentand if they get matched, that particular from collection document is attached to the input collection document in a separate array field.

Syntax: $lookup operator

{
    $lookup:
    {
        from: < "from collection" >,
        localField: < any field from "input collection" >,
        foreignField: < any field from "from collection" >,
        as: < attached array field >
    }
}
  • from: It is the field that contains the name of “from collection“, from which the documents are to be taken to join them to the documents of the input collection.
  • localField: It is any field of input collection the value of which is to be compared which the foreignField value.
  • foreignField: It is any field of from collection the value of which is to be compared which the localField value.
  • as: It is the array field in which the matched documents of from collection are to be stored.

Install Mongoose:

Step 1: You can visit the link Install mongoose to install the mongoose module. You can install this package by using this command.

npm install mongoose

Step 2: Now you can import the mongoose module in your file using:

const mongoose = require['mongoose'];

Database: We have already created collections named orders and customers in our database GFG with the following entries show in the image below:

Collections orders and customers in database GFG

Creating a Node application:

Step 1: Create package.json using the following command:

npm init

Step 2: Create file model.js which contains Schema and Model for orders and customers collections.

Yêu cầu thg 7 31, 2018 7:31 SA 4246 0 0

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.

async testLookup[book_id, limit, page]{
return await Review.aggregate[[
		{ $match: { "book_id": new mongoose.Types.ObjectId[book_id]} },
        { $lookup: {
            from: 'comments',
            localField: '_id',
            foreignField: 'review_id',
            as: 'comments'
        }},
   ]];
} 

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.

[ "user_id": {
               "_id": "5b4f090bbcb0521b24759a9c",
               "email": "",
               "is_admin": false,
               "username": "hhhhh"
           }
]

Thông tin các Model

Review

var mongoose = require['mongoose'], Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;
var ReviewSchema = new mongoose.Schema[{
  user_id: { type: ObjectId, ref: 'User' },
  book_id: { type: ObjectId },
  star: { type: Number, default: 0 },
  content: String
},
{
    timestamps: true   
}
];

Comment

var mongoose = require['mongoose'],
 Schema = mongoose.Schema,
 ObjectId = Schema.ObjectId;
var CommentSchema = new mongoose.Schema[{
  user_id: { type: ObjectId, ref: 'User' },
  review_id: { type: ObjectId, ref: 'Review' },
  content: String
}];

Chủ Đề