[英]Filter array within MongoDB document
我正在嘗試基於關閉的Twitter用戶提及來創建網絡地圖。 我將數據存儲在MongoDB中,無法弄清楚如何刪除不需要的用戶。
示例數據庫文件:
{
'user': 'user1'
'mentioned_users: ['user2', 'user3']
}
{
'user': 'user2'
'mentioned_users: ['user1', 'user3']
}
所需輸出示例:
{
'user': 'user1'
'mentioned_users': ['user2']
}
{
'user': 'user2'
'mentioned_users': ['user1']
}
user3在提到的用戶的user1和user2列表中都存在,但是user3是多余的,因為user3在集合中沒有自己的文檔。
我需要使用db.collection.find()的過濾器或其他方法,以便擺脫所有無關的用戶。
有沒有一種簡單的方法可以使用pymongo做到這一點,還是應該創建一個python解決方案?
您可以實現在MongoDB中查詢usign aggregate
。 可以試試這個
db.users.aggregate([
{$unwind: "$mentioned_users"},
{$lookup: {from: "users", localField: "mentioned_users", foreignField: "user", as: "validUser"}},
{$match: {"validUser.user": {$exists: true}}},
{
$group: {
_id: "$_id",
user: {$first: "$user"},
mentioned_users: {$push: "$mentioned_users"}
}
}
])
然后輸出將像
{
"_id" : ObjectId("5a13bc87400096bfa0b34228"),
"user" : "user1",
"mentioned_users" : ["user2"]
}
{
"_id" : ObjectId("5a13bc87400096bfa0b34229"),
"user" : "user2",
"mentioned_users" : ["user1"]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.