gpt4 book ai didi

mongodb - 在 mongodb 中搜索数组元素的查询

转载 作者:可可西里 更新时间:2023-11-01 10:03:46 26 4
gpt4 key购买 nike

我是 mongodb 的新手并且还在学习它所以我的问题可能很幼稚所以请耐心等待 :)我在 mongodb 中只有一个 json 对象,看起来像这样。

json 对象

{
"URLStore": [
{
"description": "adf description",
"url": "www.adf.com"
},
{
"description": "pqr description",
"url": "www.pqr.com"
},
{
"description": "adf description",
"url": "www.adf.com"
}
]
}

我需要查询匹配给定输入的 url 的描述。例如这里 www.adf.com 。我有一个查询 mongodb 的代码

mongodb查询

BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("URLStore.url","www.pqr.com");
BasicDBObject fields=new BasicDBObject("URLStore.description", "");
cursor = collection.find(whereQuery,fields);

但是结果是这样的

{
"_id": {
"$oid": "554b4046e4b072dd9deaf277"
},
"URLStore": [
{
"description": "pqr description"
},
{
"description": "adf description"
},
{
"description": "adf description"
}
]
}

实际上只有 1 个描述应该返回,因为具有关键字 www.pqr.com 的匹配对象只有一个。我的查询有什么问题?我在这里遗漏了什么?

我已经尝试过问题 Retrieve only the queried element in an object array in MongoDB collection但是使用那里提到的解决方案将只返回一个对象/第一个匹配项

最佳答案

使用下面的聚合管道,应该会给你想要的结果:

db.collection.aggregate([
{
"$match": {
"URLStore.url": "www.adf.com"
}
},
{
"$unwind": "$URLStore"
},
{
"$match": {
"URLStore.url": "www.adf.com"
}
},
{
"$group": {
"_id": {
"url": "$URLStore.url",
"description": "$URLStore.description"
}
}
},
{
"$project": {
"_id": 0,
"description": "$_id.description"
}
}
])

关于mongodb - 在 mongodb 中搜索数组元素的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30098838/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com