簡體   English   中英

在mongodb中搜索文檔的子文檔?

[英]Search subdocument of document in mongodb?

我想使用以下代碼使用文檔的子文檔屬性進行搜索:

Model.UserRole.aggregate(
[
    {
        $match : {
            status : { $in : ["inactive"] },
        }
    },
    {
        $lookup : {
            from: "users",
            localField: "user",
            foreignField: "_id",
            as: "user"
        }
    },
    {
        $unwind : "$user"
    },
    {
        $match : { "user.name" : { $text: { $search: keyword } } }
    }
], function(err, result) {
    callback(null, result);
});

它給了我這個錯誤:

UnhandledPromiseRejectionWarning:未處理的承諾拒絕(拒絕ID:1):MongoError:錯誤的查詢:BadValue:未知的運算符:$ text

我在那里找不到任何有效的代碼。 有什么建議大家嗎?

您應該使用regex在$ unwind之后進行搜索,因為索引僅在管道的第一階段使用。

嘗試下面提到的代碼

Model.UserRole.aggregate(
[
    {
        $match : {
            status : { $in : ["inactive"] },
        }
    },
    {
        $lookup : {
            from: "users",
            localField: "user",
            foreignField: "_id",
            as: "user"
        }
    },
    {
        $unwind : "$user"
    },
    {
        $match : { "user.name" : new RegExp(keyword, 'i') }
    }
], function(err, result) {
    callback(null, result);
});

暫無
暫無

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

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