[英]How to add a condition inside $lookup in MongoDb .aggregate()?
[英]Mongodb aggregate lookup condition
我想在獲取所有記錄時在連接記錄上設置 where 條件。 我在 $lookup 上實施了很多解決方案,但沒有得到正確的解決方案。 這是我的nodejs代碼。 希望
發布 Model 架構
const postsSchema = new mongoose.Schema({
post_title: String,
post_location: { type: mongoose.ObjectId, ref: "locations" },
});
位置 Model 架構
const locationsSchema = new mongoose.Schema({
location_name: String,
address: String,
});
Controller 代碼
var dataQuery = Posts.aggregate();
dataQuery.lookup({ from: 'locations', localField: 'post_location', foreignField: '_id', as: 'post_location' });
dataQuery.unwind("post_location");
dataQuery.exec().then(postsData => {
});
Output
[{
"_id": "5e8f179e2bd9f824fce3efd2",
"post_title": "Post title 1"
"post_location": {
"_id": "5e8ee8ae2bd9f824fce3e621",
"location_name": "Shimla",
"address": "Shimla, Himachal Pradesh, India",
},
}
{
"_id": "5e8f179e2bd9f824fce3efd2",
"post_title": "Post title 2"
"post_location": {
"_id": "5e8ee8ae2bd9f824fce3e621",
"location_name": "Goa",
"address": "Goa, India",
},
}]
我想按 location_name 或地址進行搜索。 但是沒有得到適當的代碼來實現。 請幫我?
您所要做的就是在unwind
階段之后將$match階段添加到聚合中,如下所示:
Node.js 代碼:
dataQuery.match({
$or: [
{ "post_location.location_name": new RegExp("Shimla", "i") },
{ "post_location.address": new RegExp("Shimla", "i") }
]
});
數據庫查詢:
{
$match : {
$or: [
{ "post_location.location_name": /Shimla/i) },
{ "post_location.address": /Shimla/i }
]
}
}
在這里,我們正在檢查一個單詞Shimla
在post_location
object 的location_name
或address
字段中是否可用,並僅檢索符合此條件的文檔。 當我們使用正則表達式時,我們已經包含i
以區分大小寫,這是可選的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.