Home > Database > MongoDB > body text

How to get all documents in an array that contain another document using MongoDB?

WBOY
Release: 2023-09-19 14:33:04
forward
562 people have browsed it

如何使用 MongoDB 获取数组中包含另一个文档的所有文档?

To do this, just use dot notation and find() in MongoDB. Let us create a collection containing documents -

> db.demo465.insertOne(
... {
...    id: 101,
...    details: [{
...       Name: "Chris",
...       Info: {
...          Subject: "MongoDB",
...          Marks:67
...       }
...    }, {
...          Name: "David",
...          Info: {
...             Subject: "MySQL",
...             Marks:78
...       }
...    }]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e80421bb0f3fa88e2279061")
}
>
> db.demo465.insertOne(
... {
...    id: 102,
...    details: [{
...       Name: "Bob",
...       Info: {
...          Subject: "Java",
...          Marks:45
...       }
...    }, {
...          Name: "Carol",
...          Info: {
...             Subject: "C",
...             Marks:67
...          }
...       }]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e80421cb0f3fa88e2279062")
}
Copy after login

Display all the documents in the collection with the help of find() method-

> db.demo465.find();
Copy after login

This will produce the following output-

{ "_id" : ObjectId("5e80421bb0f3fa88e2279061"), "id" : 101, "details" : [ { "Name" : "Chris",
"Info" : { "Subject" : "MongoDB", "Marks" : 67 } }, { "Name" : "David", "Info" : { "Subject" :
"MySQL", "Marks" : 78 } } ] }
{ "_id" : ObjectId("5e80421cb0f3fa88e2279062"), "id" : 102, "details" : [ { "Name" : "Bob",
"Info" : { "Subject" : "Java", "Marks" : 45 } }, { "Name" : "Carol", "Info" : { "Subject" : "C",
"Marks" : 67 } } ] }
Copy after login

The following is Query to get all documents in an array that contain another document -

> db.demo465.find({"details.Name":"Bob"});
Copy after login

This will produce the following output -

{ "_id" : ObjectId("5e80421cb0f3fa88e2279062"), "id" : 102, "details" : [ { "Name" : "Bob",
"Info" : { "Subject" : "Java", "Marks" : 45 } }, { "Name" : "Carol", "Info" : { "Subject" : "C",
"Marks" : 67 } } ] }
Copy after login

The above is the detailed content of How to get all documents in an array that contain another document using MongoDB?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template