Bạn có thể sử dụng toán tử $ in cho việc này. Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> db.searchForStringOrNumberDemo.insertOne(
{
"_id": new ObjectId(),
"StudentName": "Larry",
"StudentDetails": {
"StudentMarks": {
"StudentMongoDBMarks": [44]
}
}
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5ce2407c36e8b255a5eee944")
}
> db.searchForStringOrNumberDemo.insertOne( { "_id": new ObjectId(), "StudentName": "Larry", "StudentDetails": { "StudentMarks": { "StudentMongoDBMarks": ["44"] } } } );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ce240f036e8b255a5eee945")
} Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -
> db.searchForStringOrNumberDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5ce2407c36e8b255a5eee944"),
"StudentName" : "Larry",
"StudentDetails" : {
"StudentMarks" : {
"StudentMongoDBMarks" : [
44
]
}
}
}
{
"_id" : ObjectId("5ce240f036e8b255a5eee945"),
"StudentName" : "Larry",
"StudentDetails" : {
"StudentMarks" : {
"StudentMongoDBMarks" : [
"44"
]
}
}
} Sau đây là truy vấn để tìm kiếm chuỗi hoặc số trong một trường -
>db.searchForStringOrNumberDemo.find({"StudentDetails.StudentMarks.StudentMongoDBMarks": { "$in": ["44",44] } }); Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5ce2407c36e8b255a5eee944"),
"StudentName" : "Larry",
"StudentDetails" : {
"StudentMarks" : {
"StudentMongoDBMarks" : [
44
]
}
}
}
{
"_id" : ObjectId("5ce240f036e8b255a5eee945"),
"StudentName" : "Larry",
"StudentDetails" : {
"StudentMarks" : {
"StudentMongoDBMarks" : [
"44"
]
}
}
}