MongoDB – 配列/リストのサイズがNより大きいすべてのドキュメントを見つける
以下の文書を確認してください:
コレクション:ドメイン
{ "__id" : 1001, "domainName" : "google.com" "tag" :[ "search engine", "search", "find anything", "giant" ]}, { "__id" : 1002, "domainName" : "yahoo.com" "tag" :[ "search engine", "online portal", ]}, { "__id" : 1003, "domainName" : "mkyong.com" }
1.質問
「タグ」のサイズが3より大きいすべての文書を検索するにはどうすればよいですか?
#1.1以下のように
$ size`と
$ gt`を組み合わせてみてください:
db.domain.find( { tag: {$size: {$gt:3} } } ); null
エラーはありませんが、常にnullを返します.MongoDBはこのように動作しません。
#1.2 `$ where`演算子を使ってみてください。
db.domain.find( {$where:'this.tag.length>3'} ) MongoDB v 2.2.3 uncaught exception: error { "$err" : "error on invocation of $where function:\nJS Error: TypeError: this.tag has no properties nofile__a:0", "code" : 10071 } or MongoDB v 2.4.5 JavaScript execution failed: error: { "$err" : "JavaScript execution failed: TypeError: Cannot read property 'length' of undefined near '' ", "code" : 16722 } at src/mongo/shell/query.js:L128 >
`$ where`演算子もうまく動作していないように見えますか?
2.解決策
実際には、 `$ where`演算子は正常に動作しています。すべてのドキュメントに「タグ」フィールドが含まれているわけではなく、「プロパティがありません」というエラーが発生しました。
2.1これを修正するには、
$ exists`と
$ where`を組み合わせてみてください:
db.domain.find( {tag : {$exists:true}, $where:'this.tag.length>3'} ) { "__id" : 1001, "domainName" : "google.com" "tag" :[ "search engine", "search", "find anything", "giant" ]}
参考文献
$ where]。
http://docs.mongodb.org/manual/reference/operator/query/exists/
[MongoDB
$存在する]。
http://stackoverflow.com/questions/7811163/in-mongo-db-how-do-i-find-documents-where-array-size-is-greater-than-1
[Stackoverflow
: how do I find documents where array size is greater than 1].
http://ufasoli.blogspot.com/2012/11/mongodb-where-clause-to-query-array.html
[MongoDB
$ where節で配列の長さを問い合わせる]