Unique index into a subdocument list, indexed by one key

狂风中的少年 提交于 2019-12-11 07:43:22

问题


i need to know if is possible to have a list of objects, where the objects are uniques by day.

I have a collection with this format:

{
  domain: "google.com"
  counters: [
    { day: "2011-08-03", metric1: 10, metric_2: 15 }
    { day: "2011-08-04", metric1: 08, metric_2: 07 }
    { day: "2011-08-05", metric1: 20, metric_2: 150 }
  ]
}

I tried something like that:

db.test.ensureIndex({ domain: 1, 'counters.day': 1 }, { unique: true }).

with upsert and $push, but this not works.

Then I tried with upsert and $addToSet. but i can't set the unique fields.

I need to push a new counter, if the day exists, it should be replaced.


回答1:


Unique indexes working only for the root document, but not for the embedded. So that's mean that you can't insert two documents with same domain and counters.day. But you can insert into embedded counters duplicated rows.

I need to push a new counter, if the day exists, it should be replaced.

When you trying to insert new embedded document you should check if document with such day exists and in case if it exists make an update, otherwise insert.



来源:https://stackoverflow.com/questions/6963403/unique-index-into-a-subdocument-list-indexed-by-one-key

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!