我的MongoDB存储具有以下结构的文档:
{
"application_detail":{},
"curl_detail":{
"Curl1":{
"key1":"value1",
"key2":"value2"
},
"Curl2":{
"key1":"value1",
"key2":"value2"
},
"Curl3":{
"key1":"value1",
"key2":"value2"
},
"Curl4":{
"key1":"value1",
"key2":"value2"
},
/*total number of curls are unknown*/
}
}
如何使用express和mongoose从mongoDB中获取key1
下所有curl_detail
下的卷发?
预期输出:
{
"curl_detail": {
"Curl1": {
"key1": "value1"
},
"Curl2": {
"key1": "value1"
},
"Curl3": {
"key1": "value1"
},
"Curl4": {
"key1": "value1"
}
}
}
注意:卷发总数未知。
答案 0 :(得分:2)
我想建议您从
更改数据结构"curl_detail": {
"Curl1": {
"key1": "value1",
"key2": "value2"
},
"Curl2": {
"key1": "value1",
"key2": "value2"
}
}
到
"curl_detail": [{
"key1": "value1",
"key2": "value2"
},
{
"key1": "value1",
"key2": "value2"
}
]
将数据结构存储在数组中将使您可以更轻松地查找一些数据。同样,也不需要具有Curl1
,Curl2
等属性的对象。
对于新的数据结构,已经有了一些答案,并给出了解释:
1)Mongo find value with unknown parent key
2)Query MongoDB by value when parent key is unknown
3)MongoDB: Find document given field values in an object with an unknown key
更新
如果无法更改数据结构,请参见此解决方案(使用$arrayToObject
/ $objectToArray
来确定嵌套键的名称,例如“ Curl1”的技巧):
db.collection.aggregate([{
$addFields: {
curl_detail: {
$arrayToObject: {
$map: {
input: {
$objectToArray: "$curl_detail"
},
as: "details",
in: {
k: "$$details.k",
v: {
key1: "$$details.v.key1"
}
}
}
}
}
}
},
{
$project: {
_id: 0,
curl_detail: 1
}
}
])
这将输出以下内容:
[
{
"curl_detail": {
"Curl1": {
"key1": "value1"
},
"Curl2": {
"key1": "value1"
},
"Curl3": {
"key1": "value1"
},
"Curl4": {
"key1": "value1"
}
}
}
]
您可以通过Mongo Playground
进行检查答案 1 :(得分:1)
您可以对要查询的查询使用投影:
collection.find({}, {"curl_detail":1}, (findError, results) => {
if(findError) {
//handle the error
return;
}
// here is the expected result
console.log();
});
答案 2 :(得分:1)
如果此结果也对您有用:
[
{
"curl_detail": {
"Curl1": "value1",
"Curl2": "value1",
"Curl3": "value1",
"Curl4": "value1"
}
}
]
您可以使用$objectToArray和$arrayToObject
使用以下聚合db.collection.aggregate([
{
$addFields: {
curl_detail: {
$map: {
"input": {
"$objectToArray": "$curl_detail"
},
"as": "el",
"in": {
"k": "$$el.k",
"v": "$$el.v.key1",
}
}
}
}
},
{
$project: {
_id: 0,
curl_detail: {
$arrayToObject: "$curl_detail"
}
}
}
])
您可以将这种聚合与像这样的猫鼬一起使用,假设您的模型是MyModel:
MyModel.aggregate([
{
$addFields: {
curl_detail: {
$map: {
input: {
$objectToArray: '$curl_detail'
},
as: 'el',
in: {
k: '$$el.k',
v: '$$el.v.key1'
}
}
}
}
},
{
$project: {
_id: 0,
curl_detail: {
$arrayToObject: '$curl_detail'
}
}
}
]).then(res => {
console.log(res);
});