用 MongoDB 的查询中检索数组值?
要检索数组值,请使用点(.)表示法。我们首先使用文档创建一个集合 −
> db.retrievingArrayDemo.insertOne( { "UserDetails" : [ { "UserName" : "John", "UserAge" : 23 } ], "UserCountryName" : "AUS", "UserLoginDate" : new ISODate(), "UserMessage" : "Hello" } ); { "acknowledged" : true, "insertedId" : ObjectId("5ce9718478f00858fb12e920") } > db.retrievingArrayDemo.insertOne( { "UserDetails" : [ { "UserName" : "Sam", "UserAge" : 24 } ], "UserCountryName" : "UK", "UserLoginDate" : new ISODate(), "UserMessage" : "Bye" } ); { "acknowledged" : true, "insertedId" : ObjectId("5ce9718478f00858fb12e921") }
以下是使用 find() 方法从集合显示所有文档的查询 −
> db.retrievingArrayDemo.find().pretty();
这将生成以下输出 −
{ "_id" : ObjectId("5ce9718478f00858fb12e920"), "UserDetails" : [ { "UserName" : "John", "UserAge" : 23 } ], "UserCountryName" : "AUS", "UserLoginDate" : ISODate("2019-05-25T16:47:00.211Z"), "UserMessage" : "Hello" } { "_id" : ObjectId("5ce9718478f00858fb12e921"), "UserDetails" : [ { "UserName" : "Sam", "UserAge" : 24 } ], "UserCountryName" : "UK", "UserLoginDate" : ISODate("2019-05-25T16:47:00.670Z"), "UserMessage" : "Bye" }
以下是从 find 查询中检索数组值的查询 −
> db.retrievingArrayDemo.find({"UserCountryName" : "UK", "UserDetails.UserName":"Sam"}).pretty();
这将生成以下输出 −
{ "_id" : ObjectId("5ce9718478f00858fb12e921"), "UserDetails" : [ { "UserName" : "Sam", "UserAge" : 24 } ], "UserCountryName" : "UK", "UserLoginDate" : ISODate("2019-05-25T16:47:00.670Z"), "UserMessage" : "Bye" }
广告