Can mongoDB compare field names instead of field values?

When defining returned fields (collection.find(q, fields)) does (how) support mongoDB for comparing field names (not values)?

eg. to select a range of fields based on their name without regard to their value.

Assume that the following fields in the document (regardless of their value):

 fieldA000 fieldA001 fieldA002 fieldB000 fieldB001 fieldC000 ... 

and I want to limit the returned fields to any field name matching fieldA000 to fieldA999 (without having to explicitly define any field name) or fieldA.* (reg ex) or similar.

PS: I am currently evaluating whether we can use mongoDB instead of Cassandra, where the column range / slice selection is provided in a very simple way.

+4
source share
2 answers

Mongo has no way to map documents using regex to key names.

However, you can do this with $where , which allows you to use JavaScript execution to select each document. The disadvantage of $where is that it cannot take advantage of indexes, which is why it requires deserializing each document in the collection, which can be too slow for most applications.

Another way to do this in Mongo is with $exists and $or , but this requires explicit key names.

Such a scheme will be more efficient for this type of request, and also simplifies slicing on the server with $ :

 { dataFields: [ { id: 'A000', value: 'whatevs' }, { id: 'A001', value: 'whatevs' }, { id: 'A002', value: 'whatevs' }, { id: 'B000', value: 'whatevs' }, { id: 'B001', value: 'whatevs' }, { id: 'C000', value: 'whatevs' }, ] } 

or

 { dataFields: [ { lettter: 'A', number: 0, value: 'whatevs' }, { lettter: 'A', number: 1, value: 'whatevs' }, { lettter: 'A', number: 2, value: 'whatevs' }, { lettter: 'B', number: 0, value: 'whatevs' }, { lettter: 'B', number: 1, value: 'whatevs' }, { lettter: 'C', number: 0, value: 'whatevs' }, ] } 
+3
source

MongoDB allows you to predict each query operation, which indicates which fields should be returned.

You cannot include or exclude fields based on a template. What you can do is specify the fields to include:

db.foo.find ({}, {'A000': 1, 'A001': 1, 'B000': 1})

(This query will return the fields _id, A000, A001 and B000).

Or check the specific fields to be excluded:

db.foo.find ({}, {'B000': 0})

(This query returns all fields except B000).

See this link for more details.

In general, using such a projection to simulate cutting columns is not a good option for a document database - while data will not be returned from the db server to the client (saving network and client syntax overhead) it will still be read from disk (if only the index coverage cannot be used to return all fields), and the document should be analyzed to determine which parts to exclude.

0
source

All Articles