Filter an array in a MongoDB document

I am trying to create a network card based on the mentions of Twitter users. I store data in MongoDB and cannot figure out how to remove unwanted users.

Examples of db docs:

{
  'user': 'user1'
  'mentioned_users: ['user2', 'user3']
}
{
  'user': 'user2'
  'mentioned_users: ['user1', 'user3']
}

An example of the desired result:

{
  'user': 'user1'
  'mentioned_users': ['user2']
}
{
  'user': 'user2'
  'mentioned_users': ['user1']
}

user3 exists both in user1 and in user2 list of mentioned users, however user3 is extraneous because user3 does not have his own document in the collection.

I need either a filter using db.collection.find () or another method so that I can get rid of all unauthorized users.

Is there an easy way to do this with pymongo, or should I create a python solution?

+4
source share
1 answer

usb MongoDB 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"]
}
+1

Source: https://habr.com/ru/post/1689599/


All Articles