Tobi696
Tobi696

Reputation: 458

Why does my mongodb query return 0 results?

This is my database collection: Documents
With this go code, I try to get all the users who are either involved in the story or created the story with the given id.

func main() {
    for stf.DB == nil {
    }

    collection := stf.DB.Collection("user")
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()

    id, _ := primitive.ObjectIDFromHex("5cb4dd7e29d3dca573a73d4c")
    fter := bson.M{"_id": id}

    involvedFilter := bson.M{"stories_involved": fter}
    createdFilter := bson.M{"stories_created": fter}

    filter := bson.M{"$or": []bson.M{involvedFilter, createdFilter}}

    cur, err := collection.Find(ctx, filter)
    if err != nil {
        log.Fatal(err.Error())
    }

    defer cur.Close(ctx)

    for cur.Next(ctx) {
        var result bson.M
        err := cur.Decode(&result)

        if err != nil {
            log.Fatal(err.Error())
        }
        fmt.Println(result)
    }
    if err := cur.Err(); err != nil {
        log.Fatal(err.Error())
    }
}


The code doesn't output any errors, but it also doesn't output any objects...
Thanks for your help in advance!

Upvotes: 0

Views: 1176

Answers (1)

Wan B.
Wan B.

Reputation: 18835

Your query translates into:

{"$or":[
   {"stories_involved":{
           "_id": ObjectId("5cb4dd7e29d3dca573a73d4c")}}, 
   {"stories_created":{
           "_id":ObjectId("5cb4dd7e29d3dca573a73d4c")}}
]}

Which means that it's searching for either a document with a nested document i.e:

{stories_involved: {_id: <value>}} OR {stories_created: {_id: <value>}}.

However, the documents in the collection contains nested document array i.e:

{stories_involved: [{_id:<value>}]} OR {stories_created: [{_id:<value>}]}

This is the reason your query is not returning any value (and no error because the query syntax is correct).

There are two ways of Querying a document nested in an array using dot notation. If you know the index of the array for the document, you can just specify the position:

id, _ := primitive.ObjectIDFromHex("5cb4dd7e29d3dca573a73d4c")
involvedFilter := bson.M{"stories_involved.0._id": id}
createdFilter := bson.M{"stories_created.0._id": id}
filter := bson.M{"$or": []bson.M{involvedFilter, createdFilter}}
cur, err := collection.Find(ctx, filter)

If you do not know the index position of the document nested in the array, concatenate the name of the array field, with a dot (.) and the name of the field in the nested document:

id, _ := primitive.ObjectIDFromHex("5cb4dd7e29d3dca573a73d4c")
involvedFilter := bson.M{"stories_involved._id": id}
createdFilter := bson.M{"stories_created._id": id}
filter := bson.M{"$or": []bson.M{involvedFilter, createdFilter}}
cur, err := collection.Find(ctx, filter)

See also MongoDB: Query Documents

Upvotes: 1

Related Questions