0

I want to filter a JSON object (in the collection, called chat) which contains an array of objects. The object contains two values, leaved and user. I want to filter both, so I only get those collection entities where both values match.

Example chat entry:

{
    "_id" : ObjectId("5de8529e104e1be853907372"),
    "created_at" : ISODate("2019-12-05T00:42:35.000Z"),
    "closed" : false,
    "type" : "group",
    "creator" : ObjectId("5da976ed390587ad999e0190"),
    "messages" : [],
    "members" : [ 
        {
            "leaved" : true,
            "user" : ObjectId("5da9773c0e46aa734e4c3683")
        }, 
        {
            "leaved" : false,
            "user" : ObjectId("5dceca90ab5d5c16a7401df0")
        }
    ]
}

When I now try to filter by leaved and user, like this in mongoengine, I get the above value, but I should get none.

id = "5da9773c0e46aa734e4c3683"
chats = Chat.objects.filter(members__user=id, members__leaved=False)

If someone knows how to do it in MongoDBjs, great, I can adapt it by myself to mongoengine. :) That is why I tagged both

muuvmuuv
  • 901
  • 2
  • 13
  • 39
  • can you add your imports for ObjectID and ISODate? – oppressionslayer Dec 05 '19 at 01:38
  • @oppressionslayer what do you mean? This is mongodb json not python. I copied it from the collection. I think schema and how it has been created is unnecessary. I expect something like `..(members__user=id and members__leaved=False)` – muuvmuuv Dec 05 '19 at 01:46
  • @oppressionslayer updated my question a little, hope it is more clear now what I need. – muuvmuuv Dec 05 '19 at 08:34

1 Answers1

0

Seems like I have found the answer, thanks to myself for getting some sleep x(

id = ObjectId("5dceca90ab5d5c16a7401df0")
db.getCollection('chat').find({ 
    "$or": [
        {
            "members": { 
                "$elemMatch": { 
                    "leaved": false,
                    "user": id
                } 
            }
        },
        {
            "creator": id,
            "closed": false
        }
    ] 
})

I'll test it a little more and edit this post for the mongoengine version. After that I mark it as solved, if no one else is faster than me :)

EDIT:

That was fast...:

chats = Chat.objects.filter(
    Q(members__match={"leaved": False, "user": id}) | Q(creator=id, closed=False)
)
muuvmuuv
  • 901
  • 2
  • 13
  • 39