Để tìm kiếm theo tổ hợp hai trường, sử dụng $concat nối chuỗi và $eq so sánh trong aggregation. Tạo collection:
> db.demo502.insertOne({"FirstName":"John","LastName":"Smith"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e875534987b6e0e9d18f56d") }
> db.demo502.insertOne({"FirstName":"David","LastName":"Miller"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e87553e987b6e0e9d18f56e") }
> db.demo502.insertOne({"FirstName":"John","LastName":"Doe"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e875543987b6e0e9d18f56f") }
Hiển thị dữ liệu:
> db.demo502.find();
Kết quả:
Sử dụng
$redactvới$condđể giữ tài liệu có tên đầy đủ khớp "John Doe":> db.demo502.aggregate([ { "$redact": { "$cond": [ { "$eq": [ { "$concat": [ "$FirstName", " ", "$LastName" ] }, "John Doe" ]}, "$$KEEP", "$$PRUNE" ] }} ])Kết quả chỉ trả về tài liệu John Doe:
Cách thay thế đơn giản hơn: Sử dụng
$matchvới$expr(MongoDB 3.6+):db.demo502.find({ $expr: { $eq: [{ $concat: ["$FirstName", " ", "$LastName"] }, "John Doe"] } })Cách này hiệu suất tốt hơn
$redactcho truy vấn đơn giản.