skip to Main Content

So I have a key value object

project {
    name: "",
    createdBy: "some object id",
    
    
    sharedWith: {
       //here is a key value object to find by name
       "645c9bfe68c1438ef182bc26": { write: true }
    }
}

So I have to find all projects by key name, that project sharing with.
My request to this

I am doing it this way, and I have to apply some query filters to $or operator

return this.readProjectsQuery({
      $or: [{ createdBy: userId }, { ??? }],
    }); 

2

Answers


  1. You may review your data model, using dynamic field names is a poor design. You can use this one:

    db.collection.aggregate([
       { $set: { sharedWith_KV: { $objectToArray: "$sharedWith" } } },
       {
          $match: {
             $or: [
                { createdBy: "some object id" },
                { "sharedWith_KV.k": "645c9bfe68c1438ef182bc26" }],
          }
       },
       { $unset: "sharedWith_KV" }
    ])
    

    Mongo Playground

    Login or Signup to reply.
  2. Your project’s class or class instance method readProjectsQuery is unknown to us, but based on your shown data model and comments, you can find the documents you are looking for using a MongoDB query like this.

    db.collection.find({
      "$or": [
        {"project.createdBy": ObjectId("000000000000000000000001")},
        {"project.sharedWith.645c9bfe68c1438ef182bc26": {"$exists": true}}
      ]
    })
    

    Try it on mongoplayground.net.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search