Mongodb request without field name

I would like to query all objects that have a field containing a specific value. For example, I have two documents:

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

and I would like to get all the objects that have a field whose value is "apple", but I do not know the name of the field. Is it possible to specify a query in MongoDB to achieve this? (Numeric keys in objects are identifiers of children, and values ​​in objects are long GUIDs)

+2
source share
2 answers

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

Meanwhile, the usual way to handle this is to change the MongoDB schema. For your example, you modify the existing schema:

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

And you can create 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 do this, you can run the follwing query to find all the documents you need:

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

Note that this schema allows you to index the tags.cid and tags.value fields that are not in the original schema.

Hope this helps.

-William

+5
source

The full-text index can be used in 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); 
0
source

Source: https://habr.com/ru/post/973768/


All Articles