Home > Backend Development > Golang > Check if value in object array exists golang

Check if value in object array exists golang

WBOY
Release: 2024-02-10 13:30:21
forward
1134 people have browsed it

检查对象数组中的值是否存在 golang

#php editor Baicao will introduce you in this article how to check whether the value in the object array exists in golang. During the development process, we often need to operate and judge arrays, and in some cases, we need to check whether a certain value exists in an object array. This process may involve traversing arrays, comparing values, etc. Below we will introduce you step by step how to implement this function.

Question content

I'm trying to check if a new value exists before appending it to the mongo database, but I get an error every time.

obid, _ := primitive.objectidfromhex(id)
        query := bson.d{{key: "_id", value: obid}}
    
        var result bson.m
        er := r.collection.findone(ctx, bson.m{"_id": obid, "statusdata.status": bson.m{"$in": []string{string(p.status)}}}).decode(&result)
        if er != nil {
            if er == mongo.errnodocuments {
                return nil, errors.new(fmt.sprintf("err na  %v, %v", er.error(), p.status))
            }
            return nil, errors.new(fmt.sprintf("err norr  %v", er.error()))
        }

doc, err := utils.todoc(p)
    if err != nil {
        return nil, errors.new(err.error())
    }

    update := bson.d{{key: "$set", value: doc}}
    res := r.collection.findoneandupdate(ctx, query, update, options.findoneandupdate().setreturndocument(1))
Copy after login

My document looks like this

{
  "statusdata": [
                {
                    "status": "new",
                    "message": "you created a new dispatch request",
                    "createdat": "1657337212751",
                    "updatedat": null
                },
                {
                    "status": "assigned",
                    "message": "justin has been assigned to you",
                    "createdat": "1657412029130",
                    "updatedat": null,
                    "_id": "62ca19bdf7d864001cabfa4a"
                }
            ],
            "createdat": "2022-07-10t00:09:01.785z",
Copy after login

.... }

There are different states and I want to make sure that the same state is not sent to the database multiple times before updating the database with the new values.

type statustype string

const (
    new              statustype = "new"
    acknowledged     statustype = "acknowledged"
    assigned         statustype = "assigned"
    reject           statustype = "rejected"
    cancel           statustype = "cancelled"
    complete         statustype = "completed"
)
Copy after login

utils.todoc

func todoc(v interface{}) (doc *bson.d, err error) {
    data, err := bson.marshal(v)
    if err != nil {
        return
    }

    err = bson.unmarshal(data, &doc)
    return
}
Copy after login

Try to update

filter := bson.m{
        "_id":               obid,
        "statusdata.status": bson.m{"$ne": p.status},
    }
    update := bson.m{
        "$push": bson.m{
            "statusdata": newstatustoadd,
        },
        "$set": bson.d{{key: "$set", value: doc}},
    }

    result, err := r.collection.updateone(ctx, filter, update)
    if err != nil {
        // handle error
        return nil, errors.new(err.error())
    }
    if result.matchedcount == 0 {
        // the status already exists in statusdata
    } else if result.modifiedcount == 1 {
        // new status was added successfuly
    }
Copy after login

Return error

"write exception: write errors: [The dollar ($) prefixed field '$set'
in '$set' is not allowed in the context of an update's replacement
document. Consider using an aggregation pipeline with $replaceWith.]"
Copy after login

Workaround

Use a filter to exclude documents with the status you want to add. If the status is already present in the array, this filter will not match any documents. The update operation will only be performed if the state has not been added yet:

var newStatusToAdd = ... // This is the new statusData document you want to add

filter := bson.M{
    "_id": obId,
    "statusData.status": bson.M{"$ne": p.Status},
}
update := bson.M{
    "$push": bson.M{
        "statusData": newStatusToAdd,
    },
    "$set": doc,
}

result, err := r.collection.UpdateOne(ctx, filter, update)
if err != nil {
    // Handle error
    return
}
if result.MatchedCount == 0 {
    // The status already exists in statusData
} else if result.ModifiedCount == 1 {
    // new status was added successfuly
}
Copy after login

The above is the detailed content of Check if value in object array exists golang. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template