mongodb query without field name

妖精的绣舞 提交于 2019-11-29 08:31:23

Unfortunately, MongoDB does not support any method of querying all fields with a particular value. There is an existing Jira ticket requesting this enhancement: https://jira.mongodb.org/browse/SERVER-1248 . Feel free to comment, vote, or follow that ticket.

In the meantime, the usual way that this is handled is to change the MongoDB schema. For your example, you would change your existing schema:

{"123": "apple", "217": "pear", "179": "orange"} 
{"831": "pear", "189": "grapes"} 

And you might structure it something like this:

 { tags: [
        { cid: "123", value: "apple" },
        { cid: "217", value: "pear" },
        { cid: "179", value: "orange" },
      ]
    }
   { tags: [
        { cid: "831", value: "pear" },
        { cid: "189", value: "grapes" },
      ]
    }

Once you've done this, you can perform the follwing query to find all of the desired documents:

 db.docs.find( {'tags.value': "apple" } )

Note that this schema allows you to index the 'tags.cid' and 'tags.value' fields, which your original schema does not.

I hope this helps.

-William

You can use Full-text Index on all fields.

use dbname
db.collectionname.ensureIndex(
                           { "$**": "text" },
                           { name: "TextIndex" }
                         )

Then Search Using :

DB db = mongoClient.getDB("dbname");
DBCollection coll = db.getCollection("collectionname");
BasicDBObject query = new BasicDBObject();
            query.append("$text", new BasicDBObject("$search", searchstring));
            DBCursor cursor = coll.find(query);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!