github.com/justinjmoses/evergreen@v0.0.0-20170530173719-1d50e381ff0d/db/query.go (about)

     1  package db
     2  
     3  // Q holds all information necessary to execute a query
     4  type Q struct {
     5  	filter     interface{} // should be bson.D or bson.M
     6  	projection interface{} // should be bson.D or bson.M
     7  	sort       []string
     8  	skip       int
     9  	limit      int
    10  }
    11  
    12  // Query creates a db.Q for the given MongoDB query. The filter
    13  // can be a struct, bson.D, bson.M, nil, etc.
    14  func Query(filter interface{}) Q {
    15  	return Q{filter: filter}
    16  }
    17  
    18  func (q Q) Filter(filter interface{}) Q {
    19  	q.filter = filter
    20  	return q
    21  }
    22  
    23  func (q Q) Project(projection interface{}) Q {
    24  	q.projection = projection
    25  	return q
    26  }
    27  
    28  func (q Q) WithFields(fields ...string) Q {
    29  	projection := map[string]int{}
    30  	for _, f := range fields {
    31  		projection[f] = 1
    32  	}
    33  	q.projection = projection
    34  	return q
    35  }
    36  
    37  func (q Q) WithoutFields(fields ...string) Q {
    38  	projection := map[string]int{}
    39  	for _, f := range fields {
    40  		projection[f] = 0
    41  	}
    42  	q.projection = projection
    43  	return q
    44  }
    45  
    46  func (q Q) Sort(sort []string) Q {
    47  	q.sort = sort
    48  	return q
    49  }
    50  
    51  func (q Q) Skip(skip int) Q {
    52  	q.skip = skip
    53  	return q
    54  }
    55  
    56  func (q Q) Limit(limit int) Q {
    57  	q.limit = limit
    58  	return q
    59  }
    60  
    61  // FindOneQ runs a Q query against the given collection, applying the results to "out."
    62  // Only reads one document from the DB.
    63  func FindOneQ(collection string, q Q, out interface{}) error {
    64  	return FindOne(
    65  		collection,
    66  		q.filter,
    67  		q.projection,
    68  		q.sort,
    69  		out,
    70  	)
    71  }
    72  
    73  // FindAllQ runs a Q query against the given collection, applying the results to "out."
    74  func FindAllQ(collection string, q Q, out interface{}) error {
    75  	return FindAll(
    76  		collection,
    77  		q.filter,
    78  		q.projection,
    79  		q.sort,
    80  		q.skip,
    81  		q.limit,
    82  		out,
    83  	)
    84  }
    85  
    86  // CountQ runs a Q count query against the given collection.
    87  func CountQ(collection string, q Q) (int, error) {
    88  	return Count(collection, q.filter)
    89  }
    90  
    91  //RemoveAllQ removes all docs that satisfy the query
    92  func RemoveAllQ(collection string, q Q) error {
    93  	return Remove(collection, q.filter)
    94  }