How to query nested objects?

前端 未结 3 2155
野性不改
野性不改 2020-11-22 01:43

I have a problem when querying mongoDB with nested objects notation:

db.messages.find( { headers : { From: \"reservations@marriott.com\" } } ).count()
0
db.m         


        
3条回答
  •  感情败类
    2020-11-22 02:27

    Since there is a lot of confusion about queries MongoDB collection with sub-documents, I thought its worth to explain the above answers with examples:

    First I have inserted only two objects in the collection namely: message as:

    > db.messages.find().pretty()
    {
        "_id" : ObjectId("5cce8e417d2e7b3fe9c93c32"),
        "headers" : {
            "From" : "reservations@marriott.com"
        }
    }
    {
        "_id" : ObjectId("5cce8eb97d2e7b3fe9c93c33"),
        "headers" : {
            "From" : "reservations@marriott.com",
            "To" : "kprasad.iitd@gmail.com"
        }
    }
    >
    

    So what is the result of query: db.messages.find({headers: {From: "reservations@marriott.com"} }).count()

    It should be one because these queries for documents where headers equal to the object {From: "reservations@marriott.com"}, only i.e. contains no other fields or we should specify the entire sub-document as the value of a field.

    So as per the answer from @Edmondo1984

    Equality matches within sub-documents select documents if the subdocument matches exactly the specified sub-document, including the field order.

    From the above statements, what is the below query result should be?

    > db.messages.find({headers: {To: "kprasad.iitd@gmail.com", From: "reservations@marriott.com"}  }).count()
    0
    

    And what if we will change the order of From and To i.e same as sub-documents of second documents?

    > db.messages.find({headers: {From: "reservations@marriott.com", To: "kprasad.iitd@gmail.com"}  }).count()
    1
    

    so, it matches exactly the specified sub-document, including the field order.

    For using dot operator, I think it is very clear for every one. Let's see the result of below query:

    > db.messages.find( { 'headers.From': "reservations@marriott.com" }  ).count()
    2
    

    I hope these explanations with the above example will make someone more clarity on find query with sub-documents.

提交回复
热议问题