mongodb获取最近30分钟前插入的项目

i looking to check if exist item added in last 30 min in golang with mongodb.

this is my type models:

type PayCoin struct {
    ID            bson.ObjectId `json:"id" bson:"_id"`
    OwnerID       bson.ObjectId `json:"owner_id" bson:"owner_id"`
    PublicKey     string        `json:"public_key" bson:"public_key"`
    PrivateKey    string        `json:"-" bson:"private_key"`
    QrCode        string        `json:"qrcode" bson:"-"`
    ExchangeRate  uint64        `json:"exchange_rate" bson:"exchange_rate"`
    DepositAmount float32       `json:"deposit_amount" bson:"deposit_amount"`
    Received      uint64        `json:"received" bson:"received"`
    Completed     bool          `json:"-" bson:"completed"`
    CreatedAt     time.Time     `json:"created_at" bson:"created_at"`
    UpdatedAt     time.Time     `json:"updated_at" bson:"updated_at"`
}

this is my current function :

func (s *Storage) CoinPayExistOperation(ownerID bson.ObjectId) (*models.PayCoin, error) {
    collection := s.getCoinPay()
    var lt models.PayCoin
    timeFormat := "2006-01-02 15:04:05"
    now := time.Now()
    after := now.Add(-30*time.Minute)
    nowFormated := after.Format(timeFormat)


    err := collection.Find(bson.M{"owner_id": ownerID, "created_at": nowFormated}).One(&lt)
    return &lt, err
}

i want to check if exist items in database added in last 30 min, my current code not return any item, and in database exist. How i can do this ?

You have two small things to fix here.

  • If you want to fetch various records you should change the word one by all
  • you are doing a filter where your data time is Greater than, for this, you have to use a comparison query operator $gt

here an example how your query should looks like

collection.Find(bson.M{"owner_id": ownerID, "created_at": bson.M{"$gt": nowFormated}}).All(&lt)

Note: as this will return multiple records, remember change the lt by an slice.