英文:
Find a document via mongo-driver golang with nested array
问题
我正在尝试执行一个基本查询,该查询在一个数组中搜索特定值的文档。让我们以以下示例为例:
{
"metadata": {
"tenant": [
"tenant1",
"tenant2",
"tenant3"
]
}
}
filter := bson.M{"metadata": bson.M{"tenant": "tenant1"}}
collection := mongo.Database(DB).Collection(Collection)
result := collection.FindOne(context.Background(), filter)
这里的结果是空的,我尝试使用$elemmatch也不起作用。当我将数组从metadata中取出时,它可以工作。
请帮忙解决。
英文:
I'm trying to do a basic query that searches for a document where a specific value is inside an array.
Lets take the following example:
{
"metadata": {
"tenant": [
"tenant1",
"tenant2",
"tenant3"
]
}
}
filter := bson.M{"metadata": bson.M{"tenant": "tenant1"}}
collection := mongo.Database(DB).Collection(Collection)
result := collection.FindOne(context.Background(), filter)
The result here is empty, I tried working with $elemmatch it also didn't work.
when I take the array out of metadata it works.
Please help.
答案1
得分: 1
你的filter用于筛选具有metadata字段的文档,该字段是一个带有tenant字段且值为tenant1的文档。
要查找具有metadata字段的文档,该字段是一个文档,并且具有包含tenant1元素的tenant数组,请使用点号将字段名连接起来:
filter := bson.M{"metadata.tenant": "tenant1"}
英文:
Your filter filters for documents that has a metadata field that's a document with a tenant field with tenant1 value.
To find documents that have a metadata field being a document, having a tenant array including the tenant1 element, concatenate the field names with a dot:
filter := bson.M{"metadata.tenant": "tenant1"}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论