我有一个集合,并且那个集合有数组,我想找到那个文档的数组ID?
"_id" : ObjectId("5cde81d5f5622a42161c6065"),
"PhoneNumber" : "PhoneNumber",
"Nick" : "Nick",
"Token" : "Token1",
"MiniProfilePhoto" : "MiniPhoto",
"IsAndroid" : 1.0,
"ProfilePhotoId" : 0.0,
"ProfilePhotoKey" : 0.0,
"FriendMessages" : [
],
"Friends" : [
{
"FriendId" : ObjectId("5cde84a5f5622a42161c6068"),
"FriendState" : 2.0
},
{
"FriendId" : ObjectId("5cde740df5622a42161c6061"),
"FriendState" : 0.0
}
]
"_id" : ObjectId("5cde740df5622a42161c6061"),
"PhoneNumber" : "PhoneNumber1",
"Nick" : "Nick2",
"Token" : "Token4",
"MiniProfilePhoto" : "MiniPhoto5",
"IsAndroid" : 1.0,
"ProfilePhotoId" : 0.0,
"ProfilePhotoKey" : 0.0,
"FriendMessages" : [
],
"Friends" : [
{
"FriendId" : ObjectId("5cde81d5f5622a42161c6065"),
"FriendState" : 1.0
}
]
"_id" : ObjectId("5cde84a5f5622a42161c6068"),
"PhoneNumber" : "PhoneNumber",
"Nick" : "Nick",
"Token" : "Token",
"MiniProfilePhoto" : "MiniPhoto",
"IsAndroid" : 0.0,
"ProfilePhotoId" : 0.0,
"ProfilePhotoKey" : 0.0,
"FriendMessages" : [
],
"Friends" : [
{
"FriendId" : ObjectId("5cde81d5f5622a42161c6065"),
"FriendState" : 2.0
}
]
...
//这是我的收藏示例,ObjectId("5cde81d5f5622a42161c6065")
是两个朋友,ids "FriendId" : ObjectId("5cde84a5f5622a42161c6068")
和ObjectId("5cde740df5622a42161c6061")
,我想找到ObjectId("5cde84a5f5622a42161c6068")
和ObjectId("5cde740df5622a42161c6061")
的令牌,我如何找到我的朋友令牌?那是什么聚集物?
答案 0 :(得分:0)
这是您的汇总查询,
let query = [
{
$match: {
_id: ObjectId("5cde81d5f5622a42161c6065")
}
},
{
$project: {
Friends: 1,
Token: 1
}
},
{
$unwind: "$Friends"
},
{
$lookup: {
from: "tets",
localField: "Friends.FriendId",
foreignField: "_id",
as: "fdata"
}
},
{
$unwind: { path: "$fdata", preserveNullAndEmptyArrays: true }
},
{
$group: {
_id: "$_id",
fdata: { $push: { Token: "$fdata.Token", _id: "$fdata._id" } }
}
}
]
db.collection.aggregate(query)
输出:
{
"_id" : ObjectId("5cde81d5f5622a42161c6065"),
"fdata" : [
{
"Token" : "Token",
"_id" : ObjectId("5cde84a5f5622a42161c6068")
},
{
"Token" : "Token4",
"_id" : ObjectId("5cde740df5622a42161c6061")
}
]
}