0

I have two MongoDB collections. One is Users and another is Posts. In the user collection, each document stores a list of usernames that that particular user follows. For example,

{
    'username' : 'username',
    'following' : ['user1', 'user2', 'user3'],
    ...
}

And, each document in the Posts collection consists of an author field. Now, in order to create a news feed, I want to show only the posts of the users that a particular user follows.

{
    'content' : 'some content',
    'author' : 'user1',
    ...
}

Can I write a query in MongoEngine (Python) such that the Posts collection is queried and it returns all the documents in which the author field is one of the authors from the following list? (The list of the people that user follows) in a chronological manner.

Thank you!

petezurich
  • 9,280
  • 9
  • 43
  • 57

1 Answers1

0

Assuming you have the following model and data:

class User(Document):
    following = ListField(StringField())

class Post(Document):
    author = StringField()

User(following=['A', 'B']).save()
Post(author='B').save()

You need to have the list already (you can't query Post with a user_id directly), and then you can achieve what you want by using the __in operator:

user = User.objects.first()
print(user.following)    # [u'A', u'B']
Post.objects(author__in=user.following)    # [<Post: Post object>]
bagerard
  • 5,681
  • 3
  • 24
  • 48