如何通过ObjectId获取数组/元素中的元素



我有一个问题无法解决。我有一个Order元素,里面有Products数组

{
_id: ObjectId("5ea0bfa85422e4537478312f"),
label: "Order 01",
status: {
_id: ObjectId("5ea0bfa85422e4537478311a"),
actual: "Created",
}
products: [
{
_id: ObjectId("5ea0bfa85422e4537478312e"),
description: "Product 1"
},
{
_id: ObjectId("5ea0bfa85422e4537478312d"),
description: "Product 2"
}
]
},
{
_id: ObjectId("5ea0bfa85422e4537478312c"),
label: "Order 02",
status: {
_id: ObjectId("5ea0bfa85422e4537478311b"),
actual: "Accepted",
}
products: [
{
_id: ObjectId("5ea0bfa85422e4537478312b"),
description: "Product 3"
},
{
_id: ObjectId("5ea0bfa85422e4537478312a"),
description: "Product 4"
}
]
}

我的课程是这样的:

public class Order
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Label { get; set; }
}
public class Status
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Actual { get; set; }
}
public class Product
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Description { get; set; }
}

我想运行一个查询以返回订单,该订单包含特定的产品或状态(按其ObjectId(。以下是我如何查询产品3:的示例

//var query = "{Product.Description: 'Product 3'"}"; // it works
var query = "{Status.Id: '5ea0bfa85422e4537478311a' }";   // DIDN'T work
var query = "{Product.Id: '5ea0bfa85422e4537478312b'}";   // ALSO DIDN'T work
orders.Find(query).ToList(); 

那么,如何通过内部元素ID(Status(或任何数组元素(Products(来查询这些订单。

这是在javascript 中完成的

const query = `{"products":{ $elemMatch: { _id: ${Product.Id} } } }`;
orders.Find(query).ToList()

您必须在"产品"中使用$elemMatch来查找具有所需Id 的产品的订单

看看这是否有帮助。https://docs.mongodb.com/manual/tutorial/query-array-of-documents/

最新更新