通过引用 objects 和 MongoDB 的文本查询

Text query through referenced objects with MongoDB

我有以下结构。

书籍collection:

{
    _id: "book_1",
    title: "How to build a house",
    authorId: "author_1"
}

{
    _id: "book_2",
    title: "How to plant a tree",
    authorId: "author_2"
}

作者collection:

{
    _id: "author_1",
    name: "Adam Adamson"
}

{
    _id: "author_2",
    name: "Brent Brentson"
}

我想使用字符串 "b" 在图书 collection 中进行不区分大小写的自由文本搜索,并查找所有在标题中包含 "b" 或具有作者姓名中有 "b"。

我可以在书中嵌入作者 object 只是为了能够进行查询。但是如果作者collection中的作者名字发生变化,嵌入的作者object就会有错误的名字。

{
    _id: "book_2",
    title: "How to plant a tree",
    authorId: "author_2",
    author:
    {
        name: "Brent Brentson"
    }
}

解决这个问题的好方法是什么?

您可以使用以下查询,其中第一个查询获取与给定 regex expression query on the authors collection (using the map() method of the find() cursor) and the second query applies that array in the books collection query using the $in operator as well as using the regex pattern 匹配的作者 ID 数组,以查找在 "b" 中的图书标题:

var authorIds = db.authors.find({"name": /b/i}).map(function (doc) {return doc._id}); 
db.books.find({$or: [{"title": /b/i}, {"authorId": {"$in": authorIds} }]})

结果:

/* 0 */
{
    "_id" : "book_1",
    "title" : "How to build a house",
    "authorId" : "author_1"
}

/* 1 */
{
    "_id" : "book_2",
    "title" : "How to plant a tree",
    "authorId" : "author_2"
}

-- 更新 --

感谢@yogesh 建议使用 distinct() 方法获取作者 ID 列表的另一种方法:

var authorIds = db.authors.distinct("_id", {"name": /b/i})