mongoDB 配列が含まれているものを抽出する
mongoDBで、配列が含まれているものを抽出する手順を記述してます。
環境
- OS CentOS Stream release 9
- MongoDB 6.0.2
手順
配列が含まれているものを抽出するには、「$all」を使用します。
db.コレクション名.find( { $all: [値,値,,,] } )
実際に、以下のデータベース「hoge」にある「bar」というコレクション(テーブル)のドキュメント(レコード)を使用して動作を確認してみます。
> use hoge
> db.bar.find()
[
{
_id: ObjectId("6368b88732224041554df56c"),
name: 'bar1',
tags: [ 'japan', 'a' ],
qty: [
{ size: 'S', num: 10, color: 'blue' },
{ size: 'M', num: 100, color: 'blue' },
{ size: 'L', num: 100, color: 'green' }
]
},
{
_id: ObjectId("6368b89b32224041554df56e"),
name: 'bar2',
tags: [ 'tai', 'b' ],
qty: [ { size: 'M', num: 15, color: 'red' } ]
},
{
_id: ObjectId("6368b8a732224041554df570"),
name: 'bar3',
tags: [ 'usa', 'c' ],
qty: [
{ size: 'M', num: 20, color: 'red' },
{ size: 'LL', num: 200, color: 'yellow' },
{ size: 'XL', num: 250, color: 'blue' }
]
},
{
_id: ObjectId("6368b8b532224041554df572"),
name: 'bar3',
tags: [ 'usa', 'c', 'canada' ],
qty: [
{ size: 'M', num: 20, color: 'red' },
{ size: 'LL', num: 200, color: 'yellow' },
{ size: 'XL', num: 250, color: 'blue' }
]
}
]
「tags」に「usa」と「c」が含まれいるデータのみ抽出してみます。
> db.bar.find({tags: { $all: [ "usa","c"] }}).pretty()
[
{
_id: ObjectId("6368b8a732224041554df570"),
name: 'bar3',
tags: [ 'usa', 'c' ],
qty: [
{ size: 'M', num: 20, color: 'red' },
{ size: 'LL', num: 200, color: 'yellow' },
{ size: 'XL', num: 250, color: 'blue' }
]
},
{
_id: ObjectId("6368b8b532224041554df572"),
name: 'bar3',
tags: [ 'usa', 'c', 'canada' ],
qty: [
{ size: 'M', num: 20, color: 'red' },
{ size: 'LL', num: 200, color: 'yellow' },
{ size: 'XL', num: 250, color: 'blue' }
]
}
]
取得されていることが、確認できます。
and条件も使用できます。
> db.bar.find({ $and: [{tags:"usa"},{tags:"c"}] })
[
{
_id: ObjectId("6368b8a732224041554df570"),
name: 'bar3',
tags: [ 'usa', 'c' ],
qty: [
{ size: 'M', num: 20, color: 'red' },
{ size: 'LL', num: 200, color: 'yellow' },
{ size: 'XL', num: 250, color: 'blue' }
]
},
{
_id: ObjectId("6368b8b532224041554df572"),
name: 'bar3',
tags: [ 'usa', 'c', 'canada' ],
qty: [
{ size: 'M', num: 20, color: 'red' },
{ size: 'LL', num: 200, color: 'yellow' },
{ size: 'XL', num: 250, color: 'blue' }
]
}
]
-
前の記事
SQL Server GROUP BYした結果に条件を指定する 2022.09.15
-
次の記事
kotlin ||を使用する 2022.09.15
コメントを書く