Mongoid查询中的日期

时间:2012-03-24 14:21:57

标签: ruby-on-rails mongodb mongoid

我有一个模特:

class SimpleAction
  include Mongoid::Document
  field :set_date, :type => Date

我收集了一些数据:

  

{“_ id”:ObjectId(“4f6dd2e83a698b2518000006”),“name”:“lost”,   “notes”:“”,“set_date(1i)”:“2012”,“set_date(2i)”:“3”,   “set_date(3i)”:“25”,“set_date(4i)”:“13”,“set_date(5i)”:“57”,   “持续时间”:15,“待办事项”:“4”}

你可以在五个字段中看到mongoid存储日期 - set_date(ni)。

我有两个问题:

  • 如何通过mongo控制台客户端中的set_date字段过滤数据?像这样:

    db.simple_actions.find({ set_date : { "$lte" : new Date() } })
    

    我的查询未返回任何数据。

  • 如何通过Rails控制器中的set_date字段过滤数据?像这样:

    @simple_actions = SimpleAction.where(:set_date => { '$lte' => Date.today })
    

2 个答案:

答案 0 :(得分:14)

我建议不要使用Date,而应使用DateTime

field :set_date, :type => DateTime

现在不仅将它存储在1个字段中,如下所示:

"set_date" : ISODate("2012-03-14T17:42:27Z")

但Mongoid会正确处理您想要的各种转换:

SimpleAction.where( :set_date => { :$lte => Date.today } )

答案 1 :(得分:0)

您可以在课程时间使用它。

Rails非常适合移动设备(例如Android),当您将日期从手机发送到Api时:1482723520。(last_created = 1482723520)

你可以这样使用它:

Number.where(created_at:  { :$gte => time })

在Rails中你可以这样查询:

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:layout_width="match_parent"
app:cardBackgroundColor="@color/cardview_light_background"
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="right|center_vertical"
        android:id="@+id/txtSearchSpecialAttrTitle"
        android:padding="5dp"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/SearchSpecialAttrEditText"
        android:gravity="right|center_vertical"
        android:inputType="number"
        android:theme="@style/Theme.App.Base"
        />
</LinearLayout>

</android.support.v7.widget.CardView>
相关问题