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

问题描述 投票:0回答:1

我有一个无法解决的问题。我有一个带有Products数组的Order元素。像这样:

{
    _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(状态)或任何数组元素(产品)来查询这些顺序。

c# mongodb compass
1个回答
0
投票

这是在javascript中的完成方式

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

您必须在“产品”中使用$ elemMatch来查找包含具有所需ID的产品的订单

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

© www.soinside.com 2019 - 2024. All rights reserved.