Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB wildcard in the key of a query

Is it possible to wildcard the key in a query? For instance, given the following record, I'd like to do a .find({'a.*': 4}) This was discussed here https://jira.mongodb.org/browse/SERVER-267 but it looks like it's not been resolved.

{   'a': {     'b': [1, 2],     'c': [3, 4]   } } 
like image 911
Brad Avatar asked May 30 '11 19:05

Brad


People also ask

How do I use wildcard search in MongoDB?

Create a Wildcard Index on All Fields With this wildcard index, MongoDB indexes all fields for each document in the collection. If a given field is a nested document or array, the wildcard index recurses into the document/array and stores the value for all fields in the document/array.

How do I query a key in MongoDB?

There are two ways to do an OR query in MongoDB. "$in" can be used to query for a variety of values for a single key. "$or" is more general; it can be used to query for any of the given values across multiple keys. This matches documents with a "user_id" equal to 12345, and documents with a "user_id" equal to "joe" .

How do I capture a specific field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

What is $NOT operator in MongoDB?

Definition. $not performs a logical NOT operation on the specified <operator-expression> and selects the documents that do not match the <operator-expression> . This includes documents that do not contain the field .


1 Answers

As asked, this is not possible. The server issue you linked to is still under "issues we're not sure of".

MongoDB has some intelligence surrounding the use of arrays, and I think that's part of the complexity surrounding such a feature.

Take the following query db.foo.find({ 'a.b' : 4 } ). This query will match the following documents.

{ a: { b: 4 } } { a: [ { b: 4 } ] } 

So what does "wildcard" do here? db.foo.find( { a.* : 4 } ) Does it match the first document? What about the second?

Moreover, what does this mean semantically? As you've described, the query is effectively "find documents where any field in that document has a value of 4". That's a little unusual.

Is there a specific semantic that you're trying to achieve? Maybe a change in the document structure will get you the query you want.

like image 71
Gates VP Avatar answered Sep 17 '22 12:09

Gates VP