翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
$and
$and 集計演算子は複数の式を評価し、すべての式が と評価されたtrue場合にのみ を返しますtrue。いずれかの式が の場合false、 を返しますfalse。
パラメータ
例 (MongoDB シェル)
次の例では、 $and演算子を使用して、製品が複数の基準を満たしているかどうかを確認します。
サンプルドキュメントを作成する
db.products.insertMany([
{ _id: 1, name: "Laptop", price: 1200, inStock: true },
{ _id: 2, name: "Mouse", price: 25, inStock: false },
{ _id: 3, name: "Keyboard", price: 75, inStock: true }
]);
クエリの例
db.products.aggregate([
{
$project: {
name: 1,
price: 1,
inStock: 1,
affordable: {
$and: [
{ $lt: ["$price", 100] },
{ $eq: ["$inStock", true] }
]
}
}
}
]);
出力
[
{ _id: 1, name: 'Laptop', price: 1200, inStock: true, affordable: false },
{ _id: 2, name: 'Mouse', price: 25, inStock: false, affordable: false },
{ _id: 3, name: 'Keyboard', price: 75, inStock: true, affordable: true }
]
コードの例
$and 集計演算子を使用するコード例を表示するには、使用する言語のタブを選択します。
- Node.js
-
const { MongoClient } = require('mongodb');
async function example() {
const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
const db = client.db('test');
const collection = db.collection('products');
const result = await collection.aggregate([
{
$project: {
name: 1,
price: 1,
inStock: 1,
affordable: {
$and: [
{ $lt: ["$price", 100] },
{ $eq: ["$inStock", true] }
]
}
}
}
]).toArray();
console.log(result);
await client.close();
}
example();
- Python
-
from pymongo import MongoClient
def example():
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['products']
result = list(collection.aggregate([
{
'$project': {
'name': 1,
'price': 1,
'inStock': 1,
'affordable': {
'$and': [
{ '$lt': ['$price', 100] },
{ '$eq': ['$inStock', True] }
]
}
}
}
]))
print(result)
client.close()
example()