MongoDB 具有特定字段值的索引
MongoDB index with specific field value
美好的一天!
我有一个 collection 文件,例如
{
account_id: "accountOne"
state: stateOne
}
我想确保只有一个文档具有对 accountID<->state,其中 state 等于 stateOne,但我希望能够有许多文档,其中 state 等于不同于 stateOne 的任何值
例如,我希望能够在我的 collection:
中包含这些数据
{
account_id: "accountOne"
state: stateOne
}
{
account_id: "accountOne"
state: stateTwo
}
{
account_id: "accountOne"
state: stateTwo
}
如果我使 uniq 索引像 {account_id: 1, state: 1} 我会得到一个错误。
有没有办法通过 db 做到这一点?或者我必须通过我的服务逻辑来完成?
试试这个:
db.collection.createIndex(
{ account_id: 1, state: 1 },
{ unique: true, partialFilterExpression: { state: stateOne } }
)
美好的一天!
我有一个 collection 文件,例如
{
account_id: "accountOne"
state: stateOne
}
我想确保只有一个文档具有对 accountID<->state,其中 state 等于 stateOne,但我希望能够有许多文档,其中 state 等于不同于 stateOne 的任何值
例如,我希望能够在我的 collection:
中包含这些数据{
account_id: "accountOne"
state: stateOne
}
{
account_id: "accountOne"
state: stateTwo
}
{
account_id: "accountOne"
state: stateTwo
}
如果我使 uniq 索引像 {account_id: 1, state: 1} 我会得到一个错误。 有没有办法通过 db 做到这一点?或者我必须通过我的服务逻辑来完成?
试试这个:
db.collection.createIndex(
{ account_id: 1, state: 1 },
{ unique: true, partialFilterExpression: { state: stateOne } }
)