简体   繁体   English

Mongodb:将一个对象插入到数组中,只有当该对象的元素是唯一的

[英]Mongodb: insert an object to the array, only if an element of that object in unique

I have this collection.我有这个收藏。 I am trying to add object(item = {label: "Chrome", value: "chrome"}) to the array only if the value is unique, ie insert the whole object, item in the array foo only if array foo doesn't have any other object with the same value as item , using one MongoDB operation我正在尝试将 object(item = {label: "Chrome", value: "chrome"}) 添加到数组,仅当value是唯一的,即插入整个对象,仅当数组foo没有时才插入数组foo item '没有任何其他对象与item具有相同的值,使用一个 MongoDB 操作

foo=[{label:"IE",value:"ie"},{label:"Firefox",value:"firefox"}]

i don't think $addToSet supports duplicate detection of object fields like you want.我不认为 $addToSet 支持像您想要的那样重复检测对象字段。 however you could do it like this:但是你可以这样做:

db.bars.update(
    {
        "_id": ObjectId("5d3421a6a0100c1e083356e1"),
        "foo": {
            "$not": {
                "$elemMatch": {
                    "value": "firefox"
                }
            }
        }
    },
    {
        "$push": {
            "foo": {
                "label": "Fake Fox",
                "value": "firefox"
            }
        }
    }
)

first you match the parent object by id + that it doesn't contain "firefox" as the value in the foo object array.首先,您通过 id + 匹配父对象,它不包含“firefox”作为 foo 对象数组中的值。 then you specify a $push to add your new object to the foo array.然后您指定一个$push将您的新对象添加到 foo 数组。 that way, no duplicates will be created in the foo array.这样,不会在 foo 数组中创建重复项。

not sure what your coding language is but here's the c# code that generated the above mongo query in case anybody's interested:不确定您的编码语言是什么,但这里是生成上述 mongo 查询的 c# 代码,以防有人感兴趣:

 using MongoDB.Entities; using System.Linq; namespace StackOverflow { public class Program { public class bar : Entity { public item[] foo { get; set; } } public class item { public string label { get; set; } public string value { get; set; } } private static void Main(string[] args) { new DB("test"); var bar = new bar { foo = new[] { new item { label = "IE", value = "ie"}, new item { label = "FireFox", value = "firefox" } } }; bar.Save(); var chrome = new item { label = "Chrome", value = "chrome" }; var firefox = new item { label = "Fake Fox", value = "firefox" }; DB.Update<bar>() .Match(b => b.ID == bar.ID && !b.foo.Any(i => i.value == chrome.value)) .Modify(x => x.Push(b => b.foo, chrome)) .Execute(); DB.Update<bar>() .Match(b => b.ID == bar.ID && !b.foo.Any(i => i.value == firefox.value)) .Modify(x => x.Push(b => b.foo, firefox)) .Execute(); } } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM