1

I'm trying to do a query in mongo that basically will be...Get all documents that match this instance Id AND where the status does not equal Deleted or Rejected. I figured out how to do this in mongodb query but I'm having an issue translating it to golang mgo.

This is the mongodb query:

db.getCollection('instance_documents').find( {"$and":[
        { "status": {"$nin":['DELETED', "REJECTED"] }},
        {"_id": “instanceID”}
    ]
})

This is what I've tried so far in golang, the query does not work properly, it returns nothing:

err := appInstanceCollection.Find(bson.M{
        "$and": []bson.M{
                    {"status": bson.M{"$nin": []string{"REJECTED", "DELETED"}}},
                    {"_id": instanceID},
            },
    }).One(&instance)

1
  • To be clear, you are checking the error, right? What you're experiencing is an error-free empty result set? If that's the case, I'm worried your problem is somewhere else. Maybe it's the data? How the server is configured? Maybe some sort of data type mismatch? It certainly does not appear to be the mgo query. Does your instance struct have it's tags set up properly? Commented Sep 18, 2019 at 20:31

1 Answer 1

0

$and is unnecessary here. Mongo requires all fields in a query to be true for a document to be returned in the result set. Try setting them all in the same bson.M:

err := appInstanceCollection.Find(bson.M{
    "status": bson.M{"$nin": []string{"REJECTED", "DELETED"}},
    "_id": instanceID,
  },
}).One(&instance)

As for why your provided $and mgo query doesn't work, I'm not sure. It looks fine to me.

Sign up to request clarification or add additional context in comments.

1 Comment

I've tried that, also doesn't seem to work. Originally for status I was only ignoring the deleted ones using $ne, and that worked perfectly fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.