到目前为止,我实现的是我在对象内部获取了数组,并且我直接想要数组。
这是我的对象:
{
"_id" : ObjectId("5a28e2a1bf22d2a9ddb8f5d5"),
"description" : "My Post",
"postLikes" : [
{
"likesCount" : 0,
"likeByEmail" : "[email protected]",
"createdOn" : NumberLong(1512631701702),
"updatedOn" : NumberLong(0)
}
],
"postComments" : [
{
"comment" : "This is first comment",
"likeByEmail" : "[email protected]",
"createdOn" : NumberLong(1512643824764),
"updatedOn" : NumberLong(1512643824764)
}
],
"createdOn" : NumberLong(0),
"updatedOn" : NumberLong(0)
}
我的查询是:
db.user_posts.find({_id: ObjectId("5a28e2a1bf22d2a9ddb8f5d5")}, {postComments:1})
结果是:
{
"_id" : ObjectId("5a28e2a1bf22d2a9ddb8f5d5"),
"postComments" : [
{
"comment" : "This is first comment",
"likeByEmail" : "[email protected]",
"createdOn" : NumberLong(1512643824764),
"updatedOn" : NumberLong(1512643824764)
}
]
}
我想要的是:
[
{
"_id" : null,
"comment" : "This is first comment",
"likeByEmail" : "[email protected]",
"createdOn" : NumberLong(1512643824764),
"updatedOn" : NumberLong(1512643824764)
}
]
另外我在 Spring Boot 中使用 MongoRepository 并且那里的查询是:
@Query(value = "{'_id' : ?0}, {'postComments':1}")
它给了我同样的结果。
你可以加 "_id":false
db.user_posts.find({
_id: ObjectId("5a28e2a1bf22d2a9ddb8f5d5")
}, {
postComments: 1,
"_id": false
})
或者 "_id":0
db.user_posts.find({
_id: ObjectId("5a28e2a1bf22d2a9ddb8f5d5")
}, {
postComments: 1,
"_id": 0
})
如果您只想要文档的一部分,那么您必须使用聚合框架。幸运的是,有弹簧支撑。
正如 vaibhav 已经提到的那样find()
返回。
您可以通过这样的聚合来解决您的问题:
db.user_posts.aggregate([
{ $match: {_id: ObjectId("5a28e2a1bf22d2a9ddb8f5d5")}},
{ $unwind: "$postComments"},
{ $project: {
_id: 0,
comment: "$postComments.comment",
likeByEmail: "$postComments.likeByEmail",
createdOn: "$postComments.createdOn",
updatedOn: "$postComments.updatedOn"
}
}
])
正如@Veeram 所提议的,您也可以这样做:
db.user_posts.aggregate([
{ $match: {_id: ObjectId("5a28e2a1bf22d2a9ddb8f5d5")}},
{ $unwind: "$postComments"},
{ $replaceRoot: {"newRoot":"$postComments"}}
])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句