使用 MongoDB 查找具有数字键的对象中的值
要搜索值,只需在 MongoDB 中使用 $where。让我们创建一个包含文档的集合 -
> db.demo268.insertOne(
... {
... "details" : {
... "101" : "John",
... "1001" : "Bob"
... }
... }
...);
{
"acknowledged" : true,
"insertedId" : ObjectId("5e4816141627c0c63e7dbaaf")
}使用 find() 方法从集合中显示所有文档 -
> db.demo268.find();
这将产生以下输出 -
{ "_id" : ObjectId("5e4816141627c0c63e7dbaaf"), "details" : { "101" : "John", "1001" : "Bob" } }以下是使用数字键在对象中搜索值查询 -
> db.demo268.find({ $where:
... function() {
... for (var k in this.details) {
... if (this.details[k] == "Bob") {
... return true;
... }
... }
... }
...})这将产生以下输出 -
{ "_id" : ObjectId("5e4816141627c0c63e7dbaaf"), "details" : { "101" : "John", "1001" : "Bob" } }
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP