Đối với MongoDB 3.6 trở lên, hãy sử dụng $expr
toán tử cho phép sử dụng các biểu thức tổng hợp trong ngôn ngữ truy vấn:
var followers_count = 30;
db.locations.find({
"$expr": {
"$and": [
{ "$eq": ["$name", "development"] },
{ "$gte": [{ "$size": "$followers" }, followers_count ]}
]
}
});
Đối với các phiên bản không tương thích, bạn có thể sử dụng cả $match
và $redact
đường ống dẫn để truy vấn bộ sưu tập của bạn. Ví dụ:nếu bạn muốn truy vấn locations
bộ sưu tập có tên là 'development' và followers_count
lớn hơn 30, hãy chạy hoạt động tổng hợp sau:
const followers_count = 30;
Locations.aggregate([
{ "$match": { "name": "development" } },
{
"$redact": {
"$cond": [
{ "$gte": [ { "$size": "$followers" }, followers_count ] },
"$$KEEP",
"$$PRUNE"
]
}
}
]).exec((err, locations) => {
if (err) throw err;
console.log(locations);
})
hoặc trong một đường ống duy nhất dưới dạng
Locations.aggregate([
{
"$redact": {
"$cond": [
{
"$and": [
{ "$eq": ["$name", "development"] },
{ "$gte": [ { "$size": "$followers" }, followers_count ] }
]
},
"$$KEEP",
"$$PRUNE"
]
}
}
]).exec((err, locations) => {
if (err) throw err;
console.log(locations);
})
Ở trên sẽ trả về các vị trí chỉ với _id
tài liệu tham khảo từ người dùng. Để trả lại tài liệu người dùng làm phương tiện để "điền" mảng người theo dõi, sau đó bạn có thể nối thêm $lookup
đường ống dẫn.
Nếu phiên bản máy chủ Mongo cơ bản là 3.4 và mới hơn, bạn có thể chạy đường dẫn dưới dạng
let followers_count = 30;
Locations.aggregate([
{ "$match": { "name": "development" } },
{
"$redact": {
"$cond": [
{ "$gte": [ { "$size": "$followers" }, followers_count ] },
"$$KEEP",
"$$PRUNE"
]
}
},
{
"$lookup": {
"from": "users",
"localField": "followers",
"foreignField": "_id",
"as": "followers"
}
}
]).exec((err, locations) => {
if (err) throw err;
console.log(locations);
})
nếu không, bạn sẽ cần $unwind
mảng người theo dõi trước khi áp dụng $lookup
và sau đó nhóm lại với $group
đường ống sau đó:
let followers_count = 30;
Locations.aggregate([
{ "$match": { "name": "development" } },
{
"$redact": {
"$cond": [
{ "$gte": [ { "$size": "$followers" }, followers_count ] },
"$$KEEP",
"$$PRUNE"
]
}
},
{ "$unwind": "$followers" },
{
"$lookup": {
"from": "users",
"localField": "followers",
"foreignField": "_id",
"as": "follower"
}
},
{ "$unwind": "$follower" },
{
"$group": {
"_id": "$_id",
"created": { "$first": "$created" },
"name": { "$first": "$name" },
"followers": { "$push": "$follower" }
}
}
]).exec((err, locations) => {
if (err) throw err;
console.log(locations);
})