MongoDB查询以从JSON之类的数据中查找值?
要通过JSON数据提供值,请使用find()
以及dot(。)表示法。首先让我们创建一个包含文档的集合-
> db.findValueFromJsonDemo.insertOne( { "UserDetails": [{ "_id": new ObjectId(), "UserName": "Carol", "UserMessage": "Hi" }], "UserFriendsName": ["John","Sam"] } ); { "acknowledged" : true, "insertedId" : ObjectId("5cdf8a4cbf3115999ed511fd") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.findValueFromJsonDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cdf8a4cbf3115999ed511fd"), "UserDetails" : [ { "_id" : ObjectId("5cdf8a4cbf3115999ed511fc"), "UserName" : "Carol", "UserMessage" : "Hi" } ], "UserFriendsName" : [ "John", "Sam" ] }
以下是从json数据中查找值的查询-
> db.findValueFromJsonDemo.find({'UserDetails.UserMessage': "Hi"});
这将产生以下输出-
{ "_id" : ObjectId("5cdf8a4cbf3115999ed511fd"), "UserDetails" : [ { "_id" : ObjectId("5cdf8a4cbf3115999ed511fc"), "UserName" : "Carol", "UserMessage" : "Hi" } ], "UserFriendsName" : [ "John", "Sam" ] }