Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

advanced queuing - mongodb query without field name

I would like 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 would like to get all objects that has 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? (The numerical keys in the objects are children ids, and the values in the objects are long GUIDs)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...