英文:
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" }
])
英文:
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" }
])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论