嵌套对象上的 Mongo 索引 [英] Mongo indexing on nested object
问题描述
我的mongodb集合的结构是这样的,
My mongodb collection's structure looke like this,
{
paymentTree: {
t1: { from: "id-123", to: "id-2334", },
t2: { from: "id-1443", to: "id-567", },
t3: { from: "id-76567", to: "id-2334", },
tn: { from: "id-12n", to: "id-233n", }
}
如何在paymentTree中索引字段'to'?
How can index field 'to' in paymentTree?
推荐答案
目前无法在动态对象键中创建索引,
Currently it is not possible to create index in dynamic object key,
如果您无论如何都想实现,那么我建议您是否可以将架构结构转换为 属性模式,
If you want to achieve anyway then I would suggest if you could transform your schema structure to The Attribute Pattern,
- 将
paymentTree
对象类型改为数组类型, - 将对象更改为键值对中的数组,
k
用于树的动态键,v
用于{ from, to }
对象,
- change
paymentTree
object type to array type, - change object to array in key-value pairs,
k
for tree's dynamic key andv
for{ from, to }
object,
{
paymentTree: [
{
"k": "t1",
"v": { "from": "id-123", "to": "id-2334" }
},
{
"k": "t2",
"v": { "from": "id-1443", "to": "id-567" }
},
{
"k": "t3",
"v": { "from": "id-76567", "to": "id-2334" }
},
{
"k": "tn",
"v": { "from": "id-12n", "to": "id-233n" }
}
]
}
这种结构的好处:
创建多键单字段索引 在
to
上:Benefits of this structure:
Create Multikey Single Field Index on
to
:您可以在包含嵌套对象的数组字段上创建多键索引,
You can create multikey indexes on array fields that contain nested objects,
db.collection.createIndex({ "paymentTree.v.to": 1 });
-
Create Multikey Compound Index on
k
andto
:db.collection.createIndex({ "paymentTree.k": 1, "paymentTree.v.to": 1 });
将对象推送到数组:
您可以在更新方法(
updateOne
和updateMany
)中使用$push
将对象插入到paymentTree
数组.You can insert object to
paymentTree
array using$push
in update methods (updateOne
andupdateMany
).从数组中拉取对象:
您可以在更新方法(
updateOne
和updateMany)中使用
).$pull
从支付树数组中删除基于k
的特定对象You can remove specific object on the base of
k
from paymentTree array using$pull
in update methods (updateOne
andupdateMany
).匹配条件:
您可以使用条件运算符轻松匹配条件,
You can easily match conditions using conditional operators,
- 示例 1:
{ "paymentTree.k": "t1" }
- 例 2:
{ "paymentTree.v.to": "id-2334" } // or { "paymentTree.v.from": "id-123" }
- 例 3:
{ "paymentTree": { "$elemMatch": { "k": "t1", "v.to": "id-2334" // or "v.from": "id-123" } } }
我如何轻松选择诸如 paymentTree.t1、..:
- 查询中:
- 有一个操作符叫做$arrayToObject,你可以在投影阶段将
paymentTree
数组转换为对象($project
、$addFields
、$set
)参见 游乐场、 find()
和findOne()
投影可以接受来自 MongoDB v4.4 投影的聚合表达式和语法,与聚合的$project
阶段一致,
- In Query:
- There is a operator called $arrayToObject, you can convert
paymentTree
array to object in projection stages ($project
,$addFields
,$set
) see Playground, - The
find()
andfindOne()
projection can accept aggregation expressions and syntax from MongoDB v4.4 projection consistent with aggregation’s$project
stage,
- 您需要将
peymentTree
数组转换为客户端语言(go、node.js 等)中的对象格式.
- You need to convert
peymentTree
array to object format in your client side language (go, node.js, etc.).
这篇关于嵌套对象上的 Mongo 索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- There is a operator called $arrayToObject, you can convert
- 有一个操作符叫做$arrayToObject,你可以在投影阶段将
- 查询中: