将$ match答案从一个集合转发到Mongo中的另一个$ match [英] Forward $match answer from one collection to another $match in Mongo
问题描述
背景
我有一个mongo收藏夹标签:
I have a mongo collection tags:
...
{ "_id" : 901, "tagkey" : "color", "tagvalue" : "black" }
{ "_id" : 902, "tagkey" : "color", "tagvalue" : "white" }
{ "_id" : 903, "tagkey" : "store", "tagvalue" : "supercenter" }
{ "_id" : 904, "tagkey" : "store", "tagvalue" : "gas station" }
...
和另一个收藏集项目:
...
{ "_id" : 12, "itemname" : "truck", "tags" : [901] }
{ "_id" : 13, "itemname" : "ink", "tags" : [901, 903] }
{ "_id" : 14, "itemname" : "paper", "tags" : [902, 903] }
{ "_id" : 14, "itemname" : "gas", "tags" : [904] }
...
我正在尝试询问商店中的所有对象. 这意味着我想要一个列表的所有商品,这些商品的标签都带有一个键名:"store".因此,我将在其标签列表中输出所有包含903或904的项目. 因此,我应该获取包含墨水,纸张和气体的列表.
I am trying to ask for all the objects that are in a store. This means I want a list of all items that have a tag with a keyname: "store". So I am outputting all the items containing 903 or 904 in their tags list. So, I should get back a list containing ink, paper and gas.
问题
如何使用一个表的$match
输出作为下一个查询的值?
How do I use the output from one table's $match
as the value for my next query?
我最接近的猜测
db.tags.aggregate (
{$match: {tagkey: "store"}}, # now I have a list of all the tag items
{$match: {tags: {$elemMatch: {$in :[****]} } }} ) #Here I need to run the match query on a different collection and match the tags element to one of the _ids from the first match
)
更具体的问题
- 如何获取第二个
$match
来引用其他集合 - 如何获取该元素数组作为_id的输出
第一个
$match
- How do I get the second
$match
to refer to a different collection - How do I get that array of elements to be the _ids of the output of
the first
$match
推荐答案
您可以使用 $ ne 运算符
You can use $lookup with uncorrelated subqueries syntax to define your matching criteria and then check if there are any tags assigned to each item using $ne operator
db.items.aggregate([
{
$lookup: {
from: "tags",
let: { tags: "$tags" },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $in: [ "$_id", "$$tags" ] },
{ $eq: [ "$tagkey", "store" ] }
]
}
}
}
],
as: "tagDetails"
}
},
{
$match: {
tagDetails: {
$ne: []
}
}
}
])
这篇关于将$ match答案从一个集合转发到Mongo中的另一个$ match的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!