Mongodb 如何在mongo db中获取具有对象ID的所有用户的用户名
这是我的数据结构Mongodb 如何在mongo db中获取具有对象ID的所有用户的用户名,mongodb,mongodb-query,Mongodb,Mongodb Query,这是我的数据结构 { "_id" : ObjectId("5e38e95a5c50fe7afb44866b"), "username" : "user9", "name" : "user9", "email" : "user9@testing.com", "password" : "testing11", "dateOfBirth" : ISODate("1992-12-29T13:00:00Z"),
{
"_id" : ObjectId("5e38e95a5c50fe7afb44866b"),
"username" : "user9",
"name" : "user9",
"email" : "user9@testing.com",
"password" : "testing11",
"dateOfBirth" : ISODate("1992-12-29T13:00:00Z"),
"gender" : "Male",
"location" : "Melbourne",
"relationshipStatus" : "Married",
"visibilityStatus" : 3,
"friends" : [
ObjectId("5e38e9175c50fe7afb448667"),
ObjectId("5e38e92a5c50fe7afb448668"),
ObjectId("5e38e9405c50fe7afb448669"),
ObjectId("5e38e94c5c50fe7afb44866a")
],
"friendRequests" : [ ]
}
因此,基本上在friends数组中,我推送对象id,但我需要知道如何聚合,以便使用对象id获得名称列表,这样一个查询将给出结果-['user5'、'user6'、'user7'、'user8']或类似的内容,这些是该用户的朋友您可以尝试以下方法:-
db.user.aggregate([
{$unwind:"$friends"},
{$lookup: {
from: "user",
localField: "friends",
foreignField: "id",
as: "friendInfo"
}
},
{$group:{
_id:"$_id",
friends:{$addToSet:{$arrayElemAt:["$friendInfo.name",0]}},
name:{$first:"$name"}
}
}
]);
多亏了甘地先生的回答,我才明白。我需要使用组。您可以共享好友集合吗?您可以使用$lookup进行自加入,并获取好友的名称,前提是您正在同一集合中查找该名称。是的,但我只想为一个用户执行此操作。当我执行查找时,它会为所有用户提供名称。这只显示好友数组中的名字,我怎么看所有的名字?
db.Users.aggregate([
{$match: {_id: loggedInUser._id}},
{
$lookup: {
from: 'Users',
localField: 'friends',
foreignField: '_id',
as: 'showFriends'
}
},
{$group:{
_id:"$_id",
friends:{$push:'$showFriends.username'},
}
}
]);