簡體   English   中英

Mongodb 聚合查找條件

[英]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 }
      ]
    }
}

在這里,我們正在檢查一個單詞Shimlapost_location object 的location_nameaddress字段中是否可用,並僅檢索符合此條件的文檔。 當我們使用正則表達式時,我們已經包含i以區分大小寫,這是可選的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM