MongoDB按键名查找(不是值)

huangapple go评论126阅读模式
英文:

MongoDB find by key name (not value)

问题

Sure, here's the translated code portion:

项目 {
    名称: "",
    创建者: "某个对象ID",

    与之共享: {
        //这里是按名称查找的键值对象
        "645c9bfe68c1438ef182bc26": { 写入: true }
    }
}

所以我需要按键名称查找所有共享该项目的项目
我的请求如下

我是这样做的我必须对$or操作符应用一些查询过滤器

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

Please note that the "???"" part in the code represents a placeholder, and you should replace it with the actual query filter you intend to use.

英文:

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 }, { ??? }],
    }); 

答案1

得分: 1

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.

英文:

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](https://mongoplayground.net/p/EDp8RKFkKZp "Click me!").

答案2

得分: 0

你可以审查你的数据模型,使用动态字段名称是一个不好的设计。你可以使用这个:

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

Mongo Playground

英文:

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

huangapple
  • 本文由 发表于 2023年5月11日 18:49:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76226806.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定