Mongodb:直接以root用户身份获取子文档
使用投影,我得到子文档,但在键下,而不是根 当前查询:Mongodb:直接以root用户身份获取子文档,mongodb,aggregation-framework,Mongodb,Aggregation Framework,使用投影,我得到子文档,但在键下,而不是根 当前查询: db.collection.find({"userId" : {"$ne" : userId}, "gender":{"$in" : interestedin}}, {"profile" : 1, "_id" : 0}) 结果是这样的: [{"profile":{"firstName":"Payal",...}},{"profile":{"firstName":"Ravinder",...}}...] 我需要的是: [{"firstNa
db.collection.find({"userId" : {"$ne" : userId}, "gender":{"$in" : interestedin}}, {"profile" : 1, "_id" : 0})
结果是这样的:
[{"profile":{"firstName":"Payal",...}},{"profile":{"firstName":"Ravinder",...}}...]
我需要的是:
[{"firstName":"Payal",...},{"firstName":"Ravinder",...}...]
我问这个问题是为了确认是否存在类似的东西,因为我在这里发现了一些相关的东西:
但是,它使用聚合框架
样本文件:
{
"_id": {
"$oid": "......."
},
"id": ".......",
"facebookId": "......",
"email": "......@.....com",
"gender": "....",
"interestedIn": [
"....."
],
"isPrivate": false,
"profile": {
"name": {
"firstName": "....",
"middleName": "",
"lastName": "....."
},
"picture": "........",
"dob": 1111138064533,
"meta": {
"education": [],
"interests": [],
"music": [],
"movies": [],
"tvSeries": []
}
}
}
可以使用运算符将嵌套对象升级到根级别,请尝试:
db.collection.aggregate([
{ $match: {"userId" : {"$ne" : userId}, "gender":{"$in" : interestedin}} },
{
$replaceRoot: {
newRoot: "$profile.name"
}
}
])
可以使用运算符将嵌套对象升级到根级别,请尝试:
db.collection.aggregate([
{ $match: {"userId" : {"$ne" : userId}, "gender":{"$in" : interestedin}} },
{
$replaceRoot: {
newRoot: "$profile.name"
}
}
])
@米克尔的答案是正确的,但我想补充他的答案,因为他的语法是错误的 使用
$replaceRoot
将文档升级到顶层。它仅适用于对象,因此您希望在升级嵌套对象之前使用$unwind
提取数组数据:
db.collection.aggregate([
{ $match: {"userId" : {"$ne" : userId}, "gender":{"$in" : interestedin}} },
{ $unwind: "$profile"},
{
$replaceRoot: {
newRoot: "$profile"
}
}
])
@米克尔的答案是正确的,但我想补充他的答案,因为他的语法是错误的 使用
$replaceRoot
将文档升级到顶层。它仅适用于对象,因此您希望在升级嵌套对象之前使用$unwind
提取数组数据:
db.collection.aggregate([
{ $match: {"userId" : {"$ne" : userId}, "gender":{"$in" : interestedin}} },
{ $unwind: "$profile"},
{
$replaceRoot: {
newRoot: "$profile"
}
}
])
在问题中张贴您的示例文档,这将有助于其他人理解better@ClementAmarnath请参见编辑问题中的示例文档,这将有助于其他人理解better@ClementAmarnath请看编辑,谢谢你们,但是accepting@mickl他先回答:“谢谢你们两位,但是accepting@mickl他第一个回答说:)