查询多值数组以检索 mongodb 中的特定值
Querying a multi value array to retrieve specific value in mongodb
我的文档数据库中有一个数组元素,其中有多个 parameters.This 是单个文档的样子。我可以根据唯一的名称进行搜索。有没有办法列出与名称相关的所有技术。
"name" : "Sam",
"date" : ISODate("2020-02-05T06:34:28.453Z"),
"technology" : [
{
"technologyId" : "1",
"technologyName" : "tech1"
},
{
"technologyId" : "2",
"technologyName" : "tech2"
},
{
"technologyId" : "3",
"technologyName" : "tech3"
},
{
"technologyId" : "4",
"technologyName" : "tech4"
}
],
"sector" : [
{
"sectorId" : "1",
"sectorName" : "sector1"
},
{
"sectorId" : "2",
"sectorName" : "sector2"
},
{
"sectorId" : "3",
"sectorName" : "sector3"
},
{
"sectorId" : "4",
"sectorName" : "sector4"
}
]
这是我的简单查询
db.getCollection('myCollection').find({'name':'Sam'})
有没有办法在单个查询中检索名称的所有技术。
我的输出应该只有 tech1,tech2,tech3,tech4
.
我在考虑您没有使用同一个名称的重复技术。您可以仅投影技术名称,然后映射:
db.getCollection('myCollection')
.find({ name: 'Sam' }, { 'technology.technologyName': 1 })
.map(function(doc) { return doc['technology.technologyName'] })
使用 $match
, $project
and $map
的两阶段聚合。
查询:
db.collection.aggregate([
{
$match: {
name: "Sam"
}
},
{
$project: {
"name": "$name",
"technologies": {
$map: {
input: "$technology",
as: "t",
in: "$$t.technologyName"
}
}
}
}
]);
结果:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"name": "Sam",
"technologies": [
"tech1",
"tech2",
"tech3",
"tech4"
]
}
]
如果您不希望最终 O/P 中的 name
将其从项目阶段移除。
我的文档数据库中有一个数组元素,其中有多个 parameters.This 是单个文档的样子。我可以根据唯一的名称进行搜索。有没有办法列出与名称相关的所有技术。
"name" : "Sam",
"date" : ISODate("2020-02-05T06:34:28.453Z"),
"technology" : [
{
"technologyId" : "1",
"technologyName" : "tech1"
},
{
"technologyId" : "2",
"technologyName" : "tech2"
},
{
"technologyId" : "3",
"technologyName" : "tech3"
},
{
"technologyId" : "4",
"technologyName" : "tech4"
}
],
"sector" : [
{
"sectorId" : "1",
"sectorName" : "sector1"
},
{
"sectorId" : "2",
"sectorName" : "sector2"
},
{
"sectorId" : "3",
"sectorName" : "sector3"
},
{
"sectorId" : "4",
"sectorName" : "sector4"
}
]
这是我的简单查询
db.getCollection('myCollection').find({'name':'Sam'})
有没有办法在单个查询中检索名称的所有技术。
我的输出应该只有 tech1,tech2,tech3,tech4
.
我在考虑您没有使用同一个名称的重复技术。您可以仅投影技术名称,然后映射:
db.getCollection('myCollection')
.find({ name: 'Sam' }, { 'technology.technologyName': 1 })
.map(function(doc) { return doc['technology.technologyName'] })
使用 $match
, $project
and $map
的两阶段聚合。
查询:
db.collection.aggregate([
{
$match: {
name: "Sam"
}
},
{
$project: {
"name": "$name",
"technologies": {
$map: {
input: "$technology",
as: "t",
in: "$$t.technologyName"
}
}
}
}
]);
结果:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"name": "Sam",
"technologies": [
"tech1",
"tech2",
"tech3",
"tech4"
]
}
]
如果您不希望最终 O/P 中的 name
将其从项目阶段移除。