doudi7782
2019-04-15 20:09
浏览 108

为什么我的mongodb查询返回0个结果?

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!

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongyan1841 2019-04-16 02:09
    已采纳

    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

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题