我有一些文件。我用猫鼬和快递。 每个文档都使用以下模式构建:
mmmm yyy
导出默认用户; 对于对象“ books”中的每个文档,我可以使用不同的“ key:value”对。
例如, 第一份文件:
const userSchema = new Schema({
firstName: { type: String },
lastName: { type: String },
email: { type: String },
books: { type: Object },
});
const User = mongoose.model('User', userSchema);
第二个文档:
{
"firstName": "Lucy",
"lastName": "Red",
"email": "lucy.red@mail.com",
"books": {
"Harry Potter" : "horrible",
"Hunger Games" : "beautiful"
}
}
我想做的是查询db集合,并在数组中获取可以在每个“ books”对象中找到的所有可能的键。
对于此示例,我要检索:
{
"firstName": "Tom",
"lastName": "Brown",
"email": "tom.brown@mail.com",
"books": {
"The Great Gatsby" : "beautiful",
"Frankenstein" : "horrible"
}
}
是否存在执行此操作的方法?非常感谢。
答案 0 :(得分:1)
尝试以下方法:
db
结果如下:
db.collection.aggregate([
{
$project: {
books: { $objectToArray: "$books" }
}
},
{
$unwind: "$books"
},
{
$group: {
_id: null,
books: { $push: "$books.k" }
}
}
])