몽고 db 기록을 찾을 수 있는 어레이입니다 필드이므로 비어 있지 않습니다.

내 기록을 모두 투명지에 필드이므로 불렀으매 pictures&quot ";). 이 필드는 써줬지 배열입니다

내가 지금 여기에서 이 어레이입니다 다운로드하려는 최신 10 레코드전자문서의 비어 있지 않습니다.

하지만 내가 i& # 39, ve 봤 수립하였습니다 풀코스 haven& # 39, 이에 대한 충분한 많이 찾을 수 없다.

39 로 읽을 수 있는 옵션을 i& 달러, ve, 하지만 난 그게 더 궁금 느려터진 경우 기본 기능 및 솔루션.

그 후, 심지어 작동하지 않는.

ME.find({$where: 'this.pictures.length > 0'}).sort('-created').limit(10).execFind()

되돌려줍니다 아무것도아니야. 또한, 그런데 디스테이징하는 티s.픽토레스 것가운데 '없이' 빈 기록, 물론이겠지 되돌려줍니다 약어입니다 작동합니다

해결책

39 수도 없는 경우, 해당 문서를 don& 키를 사용할 수 있습니다.

ME.find({ pictures: { $exists: true, $not: {$size: 0} } })

몽고 db don& indexe 사용할 경우 $ # 39, t, 여기서는 관련된 크기는 더 좋은 해결책:

ME.find({ pictures: { $exists: true, $ne: [] } })

몽고 db 와 비교할 수 있습니다 '$2.6 이후 릴리스에서는 연산자에서 gt' 하지만 예상치 못한 결과를 초래할 수 있다 (rec.601 자세한 것을 확인할 수 있는 설명은 [이 오토메이티드] [1]).

ME.find({ pictures: { $gt: [] } })

[1]: # 42601244 https://stackoverflow.com/questions/14789684/find-mongodb-records-where-array-field-is-not-empty/42601244

해설 (8)

좀 더 후, 특히 보았으매 몽고 db 는 문서 및 당혹스러운 비트 함께 이 대답:

ME.find({pictures: {$exists: true, $not: {$size: 0}}})
해설 (7)

이 를 사용할 수도 있습니다.

ME.find({'pictures.0': {$exists: true}});
해설 (6)

약 2 창조하셨노 쿼리하지 신경습니까 때 - 정확성 및 성능. 내가 테스트되었습니다 염두에 두고 있는 몇 가지 방법으로 v3.0.14. 몽고 db 에서

TL; DR '데버러스도c핀드 ({num: {$ gt. 인피니티}}) '는 가장 빠르고 안정적인 (적어도 내가 테스트되었습니다 몽고 db 에서 버전).

  • 편집: 이것은 더 이상 몽고 db v3.6 작동합니다! 이에 따라 게시물로의 solution.* 대한 설명을 볼 수 있는

설정

난 w / o 바뀌엇어요 삽입됨 1k docs 문서 목록, 필드, 1k 비어 있는 수신기마다 비어 있지 않은 5 문서 목록.

for (var i = 0; i < 1000; i++) { db.doc.insert({}); }
for (var i = 0; i < 1000; i++) { db.doc.insert({ nums: [] }); }
for (var i = 0; i < 5; i++) { db.doc.insert({ nums: [1, 2, 3] }); }
db.doc.createIndex({ nums: 1 });

내가 이 isn& 인식할 수 있는 t # 39, 충분한 성능 테스트를 아래에 있지만, 내가 못지않게 배율입니다 시행하십시오 it& # 39 의 정확도를 제안하십시오 수 있을 만큼 다양한 쿼리에는 비헤이비어에 쿼리하지 사탄들 했다.

테스트

'데버러스도c핀드 ({& # 39, nums& # 39;: # 39, & # 39, {$ exists&. 진정한}}) '잘못된 결과는 되돌려줍니다 (re trying to # 39, 뭐하러요 we& 때문이다).

MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': {'$exists': true}}).count()
1005

'데버러스도c핀드 ({& # 39, nums.0& # 39;: # 39, & # 39, {$ exists&. # 39, s 도 있지만, 진정한}}) '올바른 결과를 되돌려줍니다 it& 사용하여 느린 전체 취합은 스캔 (표시문' 설명 '단계에서 콜스칸).

MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums.0': {'$exists': true}}).count()
5
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums.0': {'$exists': true}}).explain()
{
  "queryPlanner": {
    "plannerVersion": 1,
    "namespace": "test.doc",
    "indexFilterSet": false,
    "parsedQuery": {
      "nums.0": {
        "$exists": true
      }
    },
    "winningPlan": {
      "stage": "COLLSCAN",
      "filter": {
        "nums.0": {
          "$exists": true
        }
      },
      "direction": "forward"
    },
    "rejectedPlans": [ ]
  },
  "serverInfo": {
    "host": "MacBook-Pro",
    "port": 27017,
    "version": "3.0.14",
    "gitVersion": "08352afcca24bfc145240a0fac9d28b978ab77f3"
  },
  "ok": 1
}

'데버러스도c핀드 ({& # 39, nums& # 39;: {$ 존재합니다. 참, $ gt. # 39, & # 39, {$ size&. 0}}}) '되돌려줍니다 잘못된 결과를 얻을 수 있습니다. # 39 의 that& 때문에 잘못된 인덱스화할 스캑 올리면 문서가 없습니다. 하지만 느린 인덱스화할 없이 정확한 될 공산이 크다.

MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $gt: { '$size': 0 }}}).count()
0
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $gt: { '$size': 0 }}}).explain('executionStats').executionStats.executionStages
{
  "stage": "KEEP_MUTATIONS",
  "nReturned": 0,
  "executionTimeMillisEstimate": 0,
  "works": 2,
  "advanced": 0,
  "needTime": 0,
  "needFetch": 0,
  "saveState": 0,
  "restoreState": 0,
  "isEOF": 1,
  "invalidates": 0,
  "inputStage": {
    "stage": "FETCH",
    "filter": {
      "$and": [
        {
          "nums": {
            "$gt": {
              "$size": 0
            }
          }
        },
        {
          "nums": {
            "$exists": true
          }
        }
      ]
    },
    "nReturned": 0,
    "executionTimeMillisEstimate": 0,
    "works": 1,
    "advanced": 0,
    "needTime": 0,
    "needFetch": 0,
    "saveState": 0,
    "restoreState": 0,
    "isEOF": 1,
    "invalidates": 0,
    "docsExamined": 0,
    "alreadyHasObj": 0,
    "inputStage": {
      "stage": "IXSCAN",
      "nReturned": 0,
      "executionTimeMillisEstimate": 0,
      "works": 1,
      "advanced": 0,
      "needTime": 0,
      "needFetch": 0,
      "saveState": 0,
      "restoreState": 0,
      "isEOF": 1,
      "invalidates": 0,
      "keyPattern": {
        "nums": 1
      },
      "indexName": "nums_1",
      "isMultiKey": true,
      "direction": "forward",
      "indexBounds": {
        "nums": [
          "({ $size: 0.0 }, [])"
        ]
      },
      "keysExamined": 0,
      "dupsTested": 0,
      "dupsDropped": 0,
      "seenInvalidated": 0,
      "matchTested": 0
    }
  }
}

'데버러스도c핀드 ({& # 39, nums& # 39;: {$ 존재합니다. 참, $ 없습니다. # 39, & # 39, {$ size&. 하지만 성능은 되돌려줍니다 0}}}) '올바른 결과가 좋지 않습니다. It 기술적으로 에서는 인덱스화할 스캔, 그런데 아직 모든 문서 및 발전을 위해 그 후 선별됨 있다).

MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $not: { '$size': 0 }}}).count()
5
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $not: { '$size': 0 }}}).explain('executionStats').executionStats.executionStages
{
  "stage": "KEEP_MUTATIONS",
  "nReturned": 5,
  "executionTimeMillisEstimate": 0,
  "works": 2016,
  "advanced": 5,
  "needTime": 2010,
  "needFetch": 0,
  "saveState": 15,
  "restoreState": 15,
  "isEOF": 1,
  "invalidates": 0,
  "inputStage": {
    "stage": "FETCH",
    "filter": {
      "$and": [
        {
          "nums": {
            "$exists": true
          }
        },
        {
          "$not": {
            "nums": {
              "$size": 0
            }
          }
        }
      ]
    },
    "nReturned": 5,
    "executionTimeMillisEstimate": 0,
    "works": 2016,
    "advanced": 5,
    "needTime": 2010,
    "needFetch": 0,
    "saveState": 15,
    "restoreState": 15,
    "isEOF": 1,
    "invalidates": 0,
    "docsExamined": 2005,
    "alreadyHasObj": 0,
    "inputStage": {
      "stage": "IXSCAN",
      "nReturned": 2005,
      "executionTimeMillisEstimate": 0,
      "works": 2015,
      "advanced": 2005,
      "needTime": 10,
      "needFetch": 0,
      "saveState": 15,
      "restoreState": 15,
      "isEOF": 1,
      "invalidates": 0,
      "keyPattern": {
        "nums": 1
      },
      "indexName": "nums_1",
      "isMultiKey": true,
      "direction": "forward",
      "indexBounds": {
        "nums": [
          "[MinKey, MaxKey]"
        ]
      },
      "keysExamined": 2015,
      "dupsTested": 2015,
      "dupsDropped": 10,
      "seenInvalidated": 0,
      "matchTested": 0
    }
  }
}

'데버러스도c핀드 ({& # 39, nums& # 39;: {$ 존재합니다. 참, $ 이름: []}}) '가 올바른 결과를 되돌려줍니다 및 성능 아직은 약간 빠르지만 것이 좋습니다. 이 기술을 사용할 수 있어 기존 문서 목록 필드, 그런데 릭스칸 /dev/raw/raw1 함께 빈 하나씩 열거합니다 필터링하도록 있다.

MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $ne: [] }}).count()
5
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $ne: [] }}).explain('executionStats').executionStats.executionStages
{
  "stage": "KEEP_MUTATIONS",
  "nReturned": 5,
  "executionTimeMillisEstimate": 0,
  "works": 1018,
  "advanced": 5,
  "needTime": 1011,
  "needFetch": 0,
  "saveState": 15,
  "restoreState": 15,
  "isEOF": 1,
  "invalidates": 0,
  "inputStage": {
    "stage": "FETCH",
    "filter": {
      "$and": [
        {
          "$not": {
            "nums": {
              "$eq": [ ]
            }
          }
        },
        {
          "nums": {
            "$exists": true
          }
        }
      ]
    },
    "nReturned": 5,
    "executionTimeMillisEstimate": 0,
    "works": 1017,
    "advanced": 5,
    "needTime": 1011,
    "needFetch": 0,
    "saveState": 15,
    "restoreState": 15,
    "isEOF": 1,
    "invalidates": 0,
    "docsExamined": 1005,
    "alreadyHasObj": 0,
    "inputStage": {
      "stage": "IXSCAN",
      "nReturned": 1005,
      "executionTimeMillisEstimate": 0,
      "works": 1016,
      "advanced": 1005,
      "needTime": 11,
      "needFetch": 0,
      "saveState": 15,
      "restoreState": 15,
      "isEOF": 1,
      "invalidates": 0,
      "keyPattern": {
        "nums": 1
      },
      "indexName": "nums_1",
      "isMultiKey": true,
      "direction": "forward",
      "indexBounds": {
        "nums": [
          "[MinKey, undefined)",
          "(undefined, [])",
          "([], MaxKey]"
        ]
      },
      "keysExamined": 1016,
      "dupsTested": 1015,
      "dupsDropped": 10,
      "seenInvalidated": 0,
      "matchTested": 0
    }
  }
}

'데버러스도c핀드 ({& # 39, nums& # 39;: {$ gt. []}}) '가 사용되었기 때문에 예상치 못한 결과에 따라 인덱스화할 위험한 줄 수도 있다. # 39 의 발전은 스캑 that& 때문에 잘못된 인덱스화할 있는 문서가 없습니다.

MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $gt: [] }}).count()
0
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $gt: [] }}).hint({ nums: 1 }).count()
0
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $gt: [] }}).hint({ _id: 1 }).count()
5

MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $gt: [] }}).explain('executionStats').executionStats.executionStages
{
  "stage": "KEEP_MUTATIONS",
  "nReturned": 0,
  "executionTimeMillisEstimate": 0,
  "works": 1,
  "advanced": 0,
  "needTime": 0,
  "needFetch": 0,
  "saveState": 0,
  "restoreState": 0,
  "isEOF": 1,
  "invalidates": 0,
  "inputStage": {
    "stage": "FETCH",
    "filter": {
      "nums": {
        "$gt": [ ]
      }
    },
    "nReturned": 0,
    "executionTimeMillisEstimate": 0,
    "works": 1,
    "advanced": 0,
    "needTime": 0,
    "needFetch": 0,
    "saveState": 0,
    "restoreState": 0,
    "isEOF": 1,
    "invalidates": 0,
    "docsExamined": 0,
    "alreadyHasObj": 0,
    "inputStage": {
      "stage": "IXSCAN",
      "nReturned": 0,
      "executionTimeMillisEstimate": 0,
      "works": 1,
      "advanced": 0,
      "needTime": 0,
      "needFetch": 0,
      "saveState": 0,
      "restoreState": 0,
      "isEOF": 1,
      "invalidates": 0,
      "keyPattern": {
        "nums": 1
      },
      "indexName": "nums_1",
      "isMultiKey": true,
      "direction": "forward",
      "indexBounds": {
        "nums": [
          "([], BinData(0, ))"
        ]
      },
      "keysExamined": 0,
      "dupsTested": 0,
      "dupsDropped": 0,
      "seenInvalidated": 0,
      "matchTested": 0
    }
  }
}

'데버러스도c핀드 ({& # 39, nums.0': {$ gt. 인피니티}}) '올바른 결과를 되돌려줍니다 않았지만, 나쁜거라 성능 (는 전체 취합은 검사).

MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums.0': { $gt: -Infinity }}).count()
5
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums.0': { $gt: -Infinity }}).explain('executionStats').executionStats.executionStages
{
  "stage": "COLLSCAN",
  "filter": {
    "nums.0": {
      "$gt": -Infinity
    }
  },
  "nReturned": 5,
  "executionTimeMillisEstimate": 0,
  "works": 2007,
  "advanced": 5,
  "needTime": 2001,
  "needFetch": 0,
  "saveState": 15,
  "restoreState": 15,
  "isEOF": 1,
  "invalidates": 0,
  "direction": "forward",
  "docsExamined": 2005
}

'데버러스도c핀드 ({& # 39, nums& # 39;: {$ gt. 인피니티}}) '놀랍게도 이 더 잘 듭니다! 이를 통해 정확한 결과를 및 it& # 39 의 빠른 앞으로 5 docs 색인에서 스캑 상狀

MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $gt: -Infinity }}).explain('executionStats').executionStats.executionStages
{
  "stage": "FETCH",
  "nReturned": 5,
  "executionTimeMillisEstimate": 0,
  "works": 16,
  "advanced": 5,
  "needTime": 10,
  "needFetch": 0,
  "saveState": 0,
  "restoreState": 0,
  "isEOF": 1,
  "invalidates": 0,
  "docsExamined": 5,
  "alreadyHasObj": 0,
  "inputStage": {
    "stage": "IXSCAN",
    "nReturned": 5,
    "executionTimeMillisEstimate": 0,
    "works": 15,
    "advanced": 5,
    "needTime": 10,
    "needFetch": 0,
    "saveState": 0,
    "restoreState": 0,
    "isEOF": 1,
    "invalidates": 0,
    "keyPattern": {
      "nums": 1
    },
    "indexName": "nums_1",
    "isMultiKey": true,
    "direction": "forward",
    "indexBounds": {
      "nums": [
        "(-inf.0, inf.0]"
      ]
    },
    "keysExamined": 15,
    "dupsTested": 15,
    "dupsDropped": 10,
    "seenInvalidated": 0,
    "matchTested": 0
  }
}
해설 (4)

이를 시작으로 또 다른 방법으로 2.6 릴리스에서는 필드에 비교하십시오 빈 어레이입니다:

<! - 모든 언어: &gt javascript 랑 -;

ME.find({pictures: {$gt: []}})

테스트 아웃해야 셸에서는:

> db.ME.insert([
{pictures: [1,2,3]},
{pictures: []},
{pictures: ['']},
{pictures: [0]},
{pictures: 1},
{foobar: 1}
])

> db.ME.find({pictures: {$gt: []}})
{ "_id": ObjectId("54d4d9ff96340090b6c1c4a7"), "pictures": [ 1, 2, 3 ] }
{ "_id": ObjectId("54d4d9ff96340090b6c1c4a9"), "pictures": [ "" ] }
{ "_id": ObjectId("54d4d9ff96340090b6c1c4aa"), "pictures": [ 0 ] }

따라서 '그림' 은 하나 이상의 배열 요소의 위치를 제대로 dm_ownerdm_owner docs 문서 '가 아닌' 이 있는 사진, 그리고 제외시킵니다 인컨텍스트 빈 어레이입니다 어레이에서는, 혹은 실종되었다.

해설 (2)

이를 위해 다음 중 하나를 사용할 수 있습니다. 또 다시 하지 않고, 그 결과 모두 잘있게나 객체에는 don& # 39 의 주요 그 요청되었습니다 없다.

db.video.find({pictures: {$exists: true, $gt: {$size: 0}}})
db.video.find({comments: {$exists: true, $not: {$size: 0}}})
해설 (0)
{ $where: "this.pictures.length > 1" }

위치와 크기를 사용할 수 있는 달러 this.field_name.length 통과할 수 있는 비교하여 반품하십시오 어레이입니다 필드와 살펴보자. 있을 경우 어레이입니다 값보다 어레이입니다 크기 1 이상이어야 하고, 따라서 모든 어레이입니다 현장 직원들이 하나 이상의 길이 있는 어레이입니다 무슨뜻이냐믄 정보기술 (it) 은 몇 가지 data-in

해설 (0)

여기서 & # 39 만 읽어들입니다 h3&gt &lt, 모든 문서 및 pictures& # 39;;; 배열입니다 empty&lt, /h3&gt 하지 않고 있다.

ME.find({pictures: {$type: 'array', $ne: []}})

몽고 db 를 사용하는 경우 이전 버전을 3.2 '$ 유형: 4 '대신' $ 유형: # 39, & # 39, array& '. 이 솔루션을 사용할 수도 있는 디이브이 doesn& # 39, t $ 크기 # 39 의 아무 문제 때문에 there& indexe ($ size 를 사용할 수 없는 부분을 query&quot 인덱스화합니다 쿼리합니다 ";)

이 같은 다른 솔루션을 (수락됨 답):

&gt. 메리핀드 ({그림: {$ 존재합니다. 참, $ 없습니다. {$ 크기: 0}}}); &gt. 메리핀드 ({그림: {$ 존재합니다. 참, $ 이름: []}})

    • 있다 하더라도, 예를 들어, & # 39 않기 때문에 잘못된 복귀하십시오 문서를 pictures& # 39;; 는 'null', '정의되지 않은', 0, etc.
해설 (0)

'$ 엘리마치 사용하여' 연산자: 설명서에 따르면

&gt. 적어도 하나의 요소를 포함하는 문서를 일치시킵니다 엘리마치 달러 연산자입니다 어레이에서는 필드가 지정된 모든 일치하는 쿼리하지 기준은 다음과 같다.

'가치' $ 엘리마치스 배열입니다 수 있는지, 해당 비어 있지 않습니다. 따라서 같은 항목을 약간만이라도 쿼리하지

'메리핀드 ({그림: {$ 엘리마치: {$ 존재합니다. 진정한}}}) '

이 코드는 ps 의 변형, 몽고 db 에서 발견된 University& # 39 의 M121 물론이겠지.

해설 (0)

[가] [1] 을 통해 어떤 방법을 사용할 수도 있습니다 몽고 작동자 $ 존재합니다.

ME.find()
    .exists('pictures')
    .where('pictures').ne([])
    .sort('-created')
    .limit(10)
    .exec(function(err, results){
        ...
    });

[1]: http://mongoosejs.com/docs/api.html # query_Query-exists

해설 (0)
ME.find({pictures: {$exists: true}}) 

그렇게 단순 이 협력했습니다 for me.

해설 (0)