MongoDB索引可以根据某些属性是否为空对文档进行排序

时间:2019-01-28 06:16:18

标签: database mongodb mongoose

Mongo架构-

let community = new schema({
   event_id: { type: Number, required: true },
   industry: { type: String, default: "" },
   intrests: [{ type: String, default: [] }],
   look: {
     lookingFor: { type: String, default: "" }
     },
   offer: {
     offering: { type: String, default: "" }
     }
   })

Mongo查找查询-

    const query = {
           event_id : 845
    }

    const projection = {
        look : 1,
        offer : 1,
        industry : 1,
        intrests : 1
    }

    const options = { lean : true }

    models.community.find(query, projection, options, function (err, data) {
        console.log('Data ----', data)
     })

输出是-

{ _id: 5a09ac3d936a8c707f371234,
industry: 'ind 4',
intrests: [ 'int 3' ],
look: { lookingFor: 'lk 4' },
offer: { offering: 'lk 4' } },
{ _id: 5a09f543936a8c707f3a1fd0,
industry: 'ind 3',
intrests: [ 'int 1' ],
look: { lookingFor: 'lk 4' },
offer: { offering: 'lk 4' } },
{ _id: 5a0a85cf936a8c707f3f6d23,
look: { lookingFor: 'mak' },
offer: { offering: 'mak' },
industry: 'IT',
intrests: [ 'sdsdsdsd' ] },
{ _id: 5a0d65d0936a8c707f5b2e05 },
{ _id: 5a0e78d4936a8c707f655598 },
{ _id: 5a108e52936a8c707f7dea45 },
{ _id: 5a1425dd936a8c707fa9f79b },
{ _id: 5a155ec6936a8c707fb905d0 },
{ _id: 5a16627b936a8c707fc58f64 },
{ _id: 5a16aed9936a8c707fc8f133,
look: { lookingFor: 'mak' },
industry: 'Events',
intrests: [ null, null, null, null ] },
{ _id: 5a17cd0e936a8c707fd6c09c },
{ _id: 5a17cee4936a8c707fd6d5c5 },
{ _id: 5a17cf11936a8c707fd6d7b3 },
{ _id: 5a17eb87936a8c707fd80e92 }, 
{ _id: 5a1bf7bd936a8c707f09297f },
{ _id: 5a1c8948936a8c707f0febb5 },
{ _id: 5a1ef697936a8c707f2d03ed },
{ _id: 5a2690ee936a8c707f8c18b6, industry: 'App Development' }

看到其中一些是空的,我正在使用的查询将搜索或遍历集合中的所有文档。

我的问题是-

我只希望外观和要约不是有效的空文档。

有效的思路:有什么方法可以进行索引编制,将所有外观和报价为空的文档放在最后,即仅将那些有数据的文档放到开始(例如降序) )。而且我只能遍历起始文档。

例如,有1万个用户,其中只有1000个用户填写了外观和报价字段。但是,当我应用find方法时,它将遍历整个文档。

0 个答案:

没有答案