使用 NodeJS 匹配 Collection A 中的项目名称,其 ID 是 MongoDB 中 Collection B 的本地 ID
Matching an item name from Collection A, whose ID is local to Collection B in MongoDB with NodeJS
我有两个 collection,
Collection journalists: {
_id: ObjectId("6125f93f5fb88535beecd8ee")
journalist_FirstName: Shyam,
journalist_LastName: Kapoor,
.........
_id: ObjectId("6125f26b5fb88535beecd8c7"),
journalist_FirstName: Kabita
journalist_LastName: Mohan
}
Collection Stories: {
_id: ObjectId("5ec3ca7fa248314329a5a287"),
journalistId:ObjectId("6125f26b5fb88535beecd8c7"), //local id to journalists collection
storyTitle: "Joining of two tables",
briefDescription: "MongoDB joining of tables",
.....
}
现在,如果有人在搜索字段中输入“Kabita”,那么我的查询应该会显示带有标题的故事,因为“Kabita”是负责创建这个故事的记者。
"Joining of two tables"
MongoDB joining of tables
publish date: 21st Nov 2021
我的搜索查询需要考虑与记者 collection 中任何记者姓名相匹配的任何词,以及故事标题或故事描述中的任何词 collection。
在此先感谢并等待合适的回复。
aggregation
中的简单 $lookup
即可完成您的工作。你可以测试一下here.
db.journalists.aggregate([
{
"$lookup": {
"from": "Stories",
"localField": "_id",
"foreignField": "journalistId",
"as": "stories_docs"
}
}
])
然后您必须将每个故事文档分开以执行 $match
和 $unwind
{
"$unwind": "$stories_docs"
}
在此步骤之后,您可以添加一个 $match
阶段来查找您需要的信息,如果您必须在所有这些字段中查找,我将使用 $regex
但查询不会非常有效...
{
$match: {
$or: [
{
"journalist_FirstName": {
"$regex": "tables",
"$options": "i"
}
},
{
"stories_docs.briefDescription": {
"$regex": "tables",
"$options": "i"
}
},
{
"stories_docs.storyTitle": {
"$regex": "tables",
"$options": "i"
}
},
]
}
},
{
"$match": {
"stories_docs.keywordName": {
"$regex": "Heritage",
"$options": "i"
}
}
}
我有两个 collection,
Collection journalists: {
_id: ObjectId("6125f93f5fb88535beecd8ee")
journalist_FirstName: Shyam,
journalist_LastName: Kapoor,
.........
_id: ObjectId("6125f26b5fb88535beecd8c7"),
journalist_FirstName: Kabita
journalist_LastName: Mohan
}
Collection Stories: {
_id: ObjectId("5ec3ca7fa248314329a5a287"),
journalistId:ObjectId("6125f26b5fb88535beecd8c7"), //local id to journalists collection
storyTitle: "Joining of two tables",
briefDescription: "MongoDB joining of tables",
.....
}
现在,如果有人在搜索字段中输入“Kabita”,那么我的查询应该会显示带有标题的故事,因为“Kabita”是负责创建这个故事的记者。
"Joining of two tables"
MongoDB joining of tables
publish date: 21st Nov 2021
我的搜索查询需要考虑与记者 collection 中任何记者姓名相匹配的任何词,以及故事标题或故事描述中的任何词 collection。
在此先感谢并等待合适的回复。
aggregation
中的简单 $lookup
即可完成您的工作。你可以测试一下here.
db.journalists.aggregate([
{
"$lookup": {
"from": "Stories",
"localField": "_id",
"foreignField": "journalistId",
"as": "stories_docs"
}
}
])
然后您必须将每个故事文档分开以执行 $match
和 $unwind
{
"$unwind": "$stories_docs"
}
在此步骤之后,您可以添加一个 $match
阶段来查找您需要的信息,如果您必须在所有这些字段中查找,我将使用 $regex
但查询不会非常有效...
{
$match: {
$or: [
{
"journalist_FirstName": {
"$regex": "tables",
"$options": "i"
}
},
{
"stories_docs.briefDescription": {
"$regex": "tables",
"$options": "i"
}
},
{
"stories_docs.storyTitle": {
"$regex": "tables",
"$options": "i"
}
},
]
}
},
{
"$match": {
"stories_docs.keywordName": {
"$regex": "Heritage",
"$options": "i"
}
}
}