MongoDB Query Inline Document

Source: Internet
Author: User
Tags mongodb query

The documentation is as follows:

/* 0 */{  "_id": ObjectId ("55d09915331c571b60035d95"),  "title": "Hello World",  "comment": [{      "author" : "Joe",      "score": 3    }, {      "author": "Tom",      "score": 5    }, {      "author": "Jean",      "score": 9    }]} /* 1 */{  "_id": ObjectId ("55d0996a331c571b60035d96"),  "title": "Zhangsan",  "comment": [{      " Author ":" Joe ","      Score ": 7    }, {      " author ":" Suam ",      " score ": 2    }, {      " author ":" Jean ", 
    "Score": 3    }]}/* 2 */{  "_id": ObjectId ("55d099b1331c571b60035d97"),  "title": "Lisi",  "comment ": [{      " author ":" Wangwu ",      " Score ": 4    }, {      " author ":" Suam ",      " score ": 8    }, {      " Autho R ":" Tom ",      " score ": 6    }]}

Ask how to query author for Joe, and score for more than 5 comments.

The correct answer is

Db.test.find ({"comment": {"$elemMatch": {"author": "Joe", "score": {"$gte": 5}}})

If it is directly

Db.test.find ({"comment": {"author": "Joe", "score": {"$gte": 5}})
To query, the matching of the embedded document must match the entire document exactly.

If you use

Db.test.find ({"Comment.author": "Joe", "Comment.score": {"$GT": 5}})
Comments that meet auhor conditions and score conditions may not be the same, meaning that the following two documents will be queried

/* 0 */{  "_id": ObjectId ("55d09915331c571b60035d95"),  "title": "Hello World",  "comment": [{      "author" : "Joe",      "score": 3    }, {      "author": "Tom",      "score": 5    }, {      "author": "Jean",      "score": 9
   }]}/* 1 */{  "_id": ObjectId ("55d0996a331c571b60035d96"),  "title": "Zhangsan",  "comment": [{      "Author": "Joe",      "score": 7    }, {      "author": "Suam",      "score": 2    }, {      "author": "Jean", 
    "Score": 3    }]}



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

MongoDB Query Inline Document

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.