如何在 MongoDB 中搜索一個集合,以找到其中一個文件中的巢狀值?
為此,在 find() 中使用雙下劃線( __)。我們先使用文件建立一個集合 -
> db.nestedDemo.insertOne({"Information":{"__StudentName":"John Smith"}}); { "acknowledged" : true, "insertedId" : ObjectId("5e06f39125ddae1f53b621f0") } > db.nestedDemo.insertOne({"Information":{"__StudentName":"John Doe"}}); { "acknowledged" : true, "insertedId" : ObjectId("5e06f39e25ddae1f53b621f1") } > db.nestedDemo.insertOne({"Information":{"__StudentName":"Chris Brown"}}); { "acknowledged" : true, "insertedId" : ObjectId("5e06f3a625ddae1f53b621f2") }
以下是藉助 find() 方法顯示集合中所有文件的查詢 -
> db.nestedDemo.find().pretty();
這將生成以下輸出 -
{ "_id" : ObjectId("5e06f39125ddae1f53b621f0"), "Information" : { "__StudentName" : "John Smith" } } { "_id" : ObjectId("5e06f39e25ddae1f53b621f1"), "Information" : { "__StudentName" : "John Doe" } } { "_id" : ObjectId("5e06f3a625ddae1f53b621f2"), "Information" : { "__StudentName" : "Chris Brown" } }
以下是查詢集合以找到 MongoDB 中其中一個文件中的巢狀值 -
> db.nestedDemo.find({"Information.__StudentName":"John Doe"});
這將生成以下輸出 -
{ "_id" : ObjectId("5e06f39e25ddae1f53b621f1"), "Information" : { "__StudentName" : "John Doe" } }
廣告