在 MongoDB 中執行巢狀文件值搜尋?
為了搜尋值,在 MongoDB 中使用 $match。讓我們建立一個帶有文件的集合 −
> db.demo648.insertOne(
... {
... StudentInformation:
... [
... {
... Name:"John",
... CountryName:"US"
... },
... {
... Name:"David",
... CountryName:"AUS"
... },
... {
... Name:"Chris",
... CountryName:"US"
... },
... {
... Name:"Robert",
... CountryName:"UK"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9c8b286c954c74be91e6f5")
}在集合中顯示所有文件,使用 find() 方法 −
> db.demo648.find();
這將生成以下輸出 −
{ "_id" : ObjectId("5e9c8b286c954c74be91e6f5"), "StudentInformation" : [
{ "Name" : "John", "CountryName" : "US" },
{ "Name" : "David", "CountryName" : "AUS" },
{ "Name" : "Chris", "CountryName" : "US" },
{ "Name" : "Robert", "CountryName" : "UK" }
] }以下是 MongoDB 中搜索值的查詢 −
> db.demo648.aggregate([
... { $unwind: "$StudentInformation" },
... { $match: { "StudentInformation.CountryName": "US" } },
... { $project: {_id: 0}}
... ])這將生成以下輸出 −
{ "StudentInformation" : { "Name" : "John", "CountryName" : "US" } }
{ "StudentInformation" : { "Name" : "Chris", "CountryName" : "US" } }
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP