我有一些文件。我用猫鼬和快递。每个文档都使用以下架构构建:
const userSchema = new Schema({
firstName: { type: String },
lastName: { type: String },
email: { type: String },
books: { type: Object },
});
const User = mongoose.model('User', userSchema);
导出默认用户;对于对象“ books”中的每个文档,我可以有不同的“ key:value”对。
例如,第一个文档:
{
"firstName": "Lucy",
"lastName": "Red",
"email": "[email protected]",
"books": {
"Harry Potter" : "horrible",
"Hunger Games" : "beautiful"
}
}
第二份文件:
{
"firstName": "Tom",
"lastName": "Brown",
"email": "[email protected]",
"books": {
"The Great Gatsby" : "beautiful",
"Frankenstein" : "horrible"
}
}
我想做的是查询db集合,并在数组中获取可以在每个“ books”对象中找到的所有可能的键。
对于此示例,我想检索:
["Harry Potter" , "Hunger Games", "The Great Gatsby", "Frankenstein"];
是否存在执行此操作的方法?非常感谢。
尝试以下操作:
db.collection.aggregate([
{
$project: {
books: { $objectToArray: "$books" }
}
},
{
$unwind: "$books"
},
{
$group: {
_id: null,
books: { $push: "$books.k" }
}
}
])
结果将如下所示:
{
"_id" : null,
"books" : [
"Harry Potter",
"Hunger Games",
"The Great Gatsby",
"Frankenstein"
]
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句